Java.lang.Class.getMethod() 方法
描述
java.lang.Class.getMethod() 返回一个 Method 对象,该对象反映了该 Class 对象所代表的类或接口的指定公共成员方法。 name 参数是一个字符串,指定所需方法的简单名称。
parameterTypes 参数是一个 Class 对象数组,它们按照声明的顺序标识方法的形式参数类型。 如果 parameterTypes 为 null,则将其视为空数组。.
声明
以下是 java.lang.Class.getMethod() 方法的声明。
public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
参数
name − 这是方法的名称。
parameterTypes − 这是参数列表。
返回值
此方法返回与指定名称和参数类型匹配的 Method 对象。
异常
NoSuchMethodException − 如果没有找到匹配的方法或者名称是 <init> 或<clinit>。
NullPointerException − 如果名称为空
SecurityException − 如果存在安全管理员 s。
示例
下面的例子展示了 java.lang.Class.getMethod() 方法的使用。
package com.tutorialspoint;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
ClassDemo cls = new ClassDemo();
Class c = cls.getClass();
try {
// parameter type is null
Method m = c.getMethod("show", null);
System.out.println("method = " + m.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
try {
// method Long
Class[] cArg = new Class[1];
cArg[0] = Long.class;
Method lMethod = c.getMethod("showLong", cArg);
System.out.println("method = " + lMethod.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
}
public Integer show() {
return 1;
}
public void showLong(Long l) {
this.l = l;
}
long l = 78655;
}
让我们编译并运行上面的程序,这将产生下面的结果 −
method = public java.lang.Integer com.tutorialspoint.ClassDemo.show() method = public void com.tutorialspoint.ClassDemo.showLong(java.lang.Long)

