反射中方法的获取和执行

来源:互联网 发布:知乎首页代码 编辑:程序博客网 时间:2024/06/05 22:33

解剖Person类中的方法.

第一步.获取Person类的字节码对象

Class clazz =Class.forName(“cn.itcast.bean.Person”)

//第二步,通过Class类中的方法,获取指定类中的内容

Method[] methods=clazz.getMethods();//获取的是共有的.包括继承的

Methods =clazz.getDeclaredMethods();//获取本类中的所有方法.(不包括继承的)

 

//获取一个方法,并执行

Mehtod method = clazz.getMethod(“show”,null)//获取名称为show的方法,没有参数传null;传的方法名和参数的类型,(类型.class)

通过Class对象的newInstance方法获取指定类的一个实例

Object obj =clazz.newInstance();//其实是在调用当前字节码文件对象中的空参数构造函数在进行初始化.

method.invoke(obj,null);//通过invoke()方法传对象和参数调用方法.

 

//获取指定私有方法

Method method =clazz.getDeclaredMethod(“function”,null);

因为是私有,不可以直接访问,但是可以通过其父类的方法改变其访问权限,实现暴力访问.

mehod.setAccessible(true);//实现暴力访问,setAccessible类中方法

Object obj =clazz.newInstance();

method.invoke(obj,null);

//获取字段跟方法一样,将Method改成File就行

 

 

获取指定类的构造方法

Method method =clazz.getDeclaredMethod(“function”,null);

//获取一个指定额构造函数,并通过该构造函数对象进行对象的初始化.

参数是类型对应的Class文件.

Constructorconstructor = clazz.getConstructor(String.class,int.class);

Object obj = constructor.newInstance(“张三”,30);//构造函数进行初始化

Method method =clazz.getMethod(“show”,null);

Method.invoke(obj,null);


public class Person {
public String name;
private int age;

Person(){

}
public Person(String name,int age){
this.name = name;
this.age = age;
}

public void show(){
System.out.println(name+"..........show run....."+age);
}

private void method(String str){
System.out.println("method........."+str);
}
}