Class是对一个类的描述
类的属性:Field
类的方法:Method
类的构造器:Constructor
Method:对应类中的方法
1.获取Method
1.1获取类的方法的数组:cla.getDeclareMethods();
1.2获取类的指定的方法:getDeclaredMethod(String, Class...) 第一个参数是方法名,第二个是Class类型的可变参数
类的属性:Field
类的方法:Method
类的构造器:Constructor
Method:对应类中的方法
1.获取Method
1.1获取类的方法的数组:cla.getDeclareMethods();
1.2获取类的指定的方法:getDeclaredMethod(String, Class...) 第一个参数是方法名,第二个是Class类型的可变参数
1.3通过Method对象执行方法,调用invoke
public Object invoke(Object obj,Object...args) obj:执行那个对象的方法 args:执行方法需要传入的参数
public void testMethod() throws Exception{
Class cla = Class.forName("cn.reflection.Person");
//1.获取对应类的方法,不能获取private方法
Method[] methods = cla.getMethods();
for(Method method:methods){
System.out.println(method.getName());
}
//2.获取所有方法,包括获取private方法,但只获取当前类的声明的所有方法
Method[] methods2 = cla.getDeclaredMethods();
for(Method method:methods2){
System.out.println("~"+method.getName());
}
//3.获取指定的方法,
//getDeclaredMethod("setName", String.class),第一个是方法名,第二个是.class类型的可变参数
Method methods3 = cla.getDeclaredMethod("setName", String.class);
System.out.println(methods3);
Method method4 = cla.getDeclaredMethod("setName", String.class,int.class);
System.out.println(method4);
//4.执行方法
Object obj = cla.newInstance();
method4.invoke(obj,"class",01);
}