在 Java 中根据名称和参数类型获取声明的方法


可以使用 java.lang.Class.getDeclaredMethod() 方法根据名称和参数类型获取声明的方法。此方法接受两个参数,即方法的名称和方法的参数数组。

getDeclaredMethod() 方法返回一个 Method 对象,该对象表示与方法名称和参数数组(作为参数)匹配的类的该方法。

以下给出了一个使用 getDeclaredMethod() 方法根据名称和参数类型获取声明方法的程序示例:

示例

 在线演示

package Test;
import java.lang.reflect.*;
public class Demo {
   public String str;
   private Integer func1() {
      return 1;
   }
   public void func2(String str) {
      this.str = "Stars";
   }
   public static void main(String[] args) {
      Demo obj = new Demo();
      Class c = obj.getClass();
      try {
         Method m1 = c.getDeclaredMethod("func1", null);
         System.out.println("The method is: " + m1.toString());
         Class[] argument = new Class[1];
         argument[0] = String.class;
         Method m2 = c.getDeclaredMethod("func2", argument);
         System.out.println("The method is: " + m2.toString());
      }
      catch(NoSuchMethodException e){
         System.out.println(e.toString());
      }
   }
}

输出

The method is: private java.lang.Integer Test.Demo.func1()
The method is: public void Test.Demo.func2(java.lang.String)

现在让我们了解一下上面的程序。

在 Demo 类中,有两个方法 func1() 和 func2()。演示此方法的代码片段如下:

public String str;
private Integer func1() {
   return 1;
}
public void func2(String str) {
   this.str = "Stars";
}

在 main() 方法中,创建了一个 Demo 类的对象 obj。然后使用 getClass() 获取 obj 的类 c。最后,使用 getDeclaredMethod() 方法获取方法 func1() 和 func2(),并显示它们。演示此方法的代码片段如下:

Demo obj = new Demo();
Class c = obj.getClass();
try {
   Method m1 = c.getDeclaredMethod("func1", null);
   System.out.println("The method is: " + m1.toString());
   Class[] argument = new Class[1];
   argument[0] = String.class;
   Method m2 = c.getDeclaredMethod("func2", argument);
   System.out.println("The method is: " + m2.toString());
}

更新于: 2020-06-25

869 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.