使用Class对象可以获取类定义的所有成员方法,获取的成员方法以Method类型的对象或数组方式返回,每个Method对象代表一个成员方法,利用Method对象提供的方法可以操作该类的成员方法。
Class类定义了如下方法,用于访问类的成员方法。
● Method[] getMethods()
该方法返回包含方法对象的数组,该数组包含该类对象表示的类或接口的所有公共方法,包括由该类或接口声明的方法和从超类和超接口继承的方法。
● Method getMethod(String name, Class<?>... parameterTypes)
该方法返回一个方法对象,该方法对象由该类对象表示的类或接口的指定公共成员方法。name参数是方法的名称,parameterTypes参数是一个类对象数组,它按声明的顺序标识方法的形式参数类型,如果方法没有参数,该参数可以为空。
● Method[] getDeclaredMethods()
该方法返回一个包含方法对象的数组,该数组包含该类对象表示的类或接口的所有声明方法,包括公共、受保护、默认(包)访问和私有方法,但不包括继承的方法。
● Method getDeclaredMethod (String name, Class<?>... parameterTypes)
该返回一个方法对象,该方法对象由该类对象表示的类或接口的指定声明方法。name参数是方法的名称,parameterTypes参数是一个类对象数组,它按声明的顺序标识方法的形式参数类型,如果方法没有参数,该参数可以为空。
案例1:建立MethodTest1测试类,应用Class类的getMethod()和getDeclaredMethods()等方法获取Person类的成员方法。
在PCoreUnit8项目新建method包,在method包下新建MethodTest1类。代码如下:
package method;
import java.lang.reflect.Method;
import constructor.Person;
/**
* @ClassName: MethodTest1
* @Description: 反射(访问类的成员方法)案例1
* @author 编程训练营
* @date
*
*/
public class MethodTest1 {
/**
* @Title: main
* @Description: Java程序入口main方法
* @param @param args 参数
*
* @return void 返回类型 @throws
*/
public static void main(String[] args) {
// 获取Person类的Class对象
Class<?> personClass = (Class) Person.class;
try {
// 通过class.getMethods()获取所有具有public权限的成员方法
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println("通过class.getMethods()获取所有具有public权限的成员方法:" + method);
}
// 通过class.getMethod(name)获取指定名称的成员方法
// 成员方法必须是public访问权限
Method method1 = personClass.getMethod("showPerson");
System.out.println("通过class.getMethod(name,parameterTypes)获取指定名称的成员方法" + method1);
// 通过class.getDeclaredMethods获取所有的成员方法
Method[] methods1 = personClass.getDeclaredMethods();
for (Method dmethod : methods1) {
System.out.println("通过class.getDeclaredMethods获取所有的成员方法:" + dmethod);
}
// 通过class.getDeclaredMethod(name,parameterTypes)获取指定名称的成员方法
Method method2 = personClass.getDeclaredMethod("setName",String.class);
System.out.println("通过class.getDeclaredField(name,parameterTypes)获取指定名称的成员方法" + method2);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}MethodTest1程序程序应用Person类的静态成员变量class获取Class对象,分别调用Class类的getMethods()、getMethod()、getDeclaredMethods()、getDeclaredMethod()方法获取Person类的成员方法。
Method类在java.lang.reflect包内,需要使用import语句导入Method类。
程序执行结果如下图所示:
