版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
测试类1
package reflectPrivateMethod;
public class Test1 {
//私有方法
private void func1() {
System.out.println("this is a private method!");
}
}
测试类2
package reflectPrivateMethod;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
run();
}
public static void run() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取类class信息
Class c=Class.forName("reflectPrivateMethod.Test1");
//通过class信息实例化对象
Test1 t1=(Test1)c.newInstance();
//获取该类声明的私有方法
Method m=c.getDeclaredMethod("func1", null);
//打开权限
m.setAccessible(true);
//调用方法
m.invoke(t1, null);
}
}