JAVA通过反射调用类的私有方法
实际在JAVA11中可运行
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
class Father {
int father1 = 1;
static int father2 = 2;
//有参构造函数
//public Father(int a, int b) {
// System.out.println("a * b"+ a * b);
//}
public void run() {
System.out.println("father is run");
}
//要调用的私有方法
private void runFather(int a, int b) {
System.out.println(a + b);
System.out.println("123");
}
}
// 在这里有很多断言啥的,可以忽视,不加会报错,尤其是try catch语句
public class Test{
public static void main(String[] args) {
Class<?> f = null;
try {
f = Class.forName("Father");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method my = null;
try {
assert f != null;
//如果是无参的方法,就把后面两个参数去掉即可
//getmethod只能获取public方法
my = f.getDeclaredMethod("runFather", Integer.TYPE, Integer.TYPE);
//效果相同
//my = f.getDeclaredMethod("runFather", int.class, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
assert my != null;
//私有方法必须获取权限
my.setAccessible(true);
try {
//这里有些博客里说的方法已经过期了,同样如果是无参的私有方法,就把1,3去掉(传入的参数)
//cls.newInstance()得到对象类型已经弃用(只能调用无参构造函数)
//getDeclaredConstructor().newInstance()得到实例化对象
//当类只有无参构造函数时,可以这么写
my.invoke(f.getDeclaredConstructor().newInstance(), 1, 3);
//当类有有参构造函数时,要这么写
//getDeclaredConstructor(int.class, int.class)传入构造函数参数类型
//.newInstance(1,3)传入参数值,输入会连带构造函数的输出
//my.invoke(f.getDeclaredConstructor(int.class, int.class).newInstance(1,3), 1, 3);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}