反射获取一个类的私有方法

比较简单

Github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AccessPrivateMember {

public static void main(String[] args) {
try {
Class c = Class.forName("com.example.reflect.HelloService");
//能获取所有有访问权限的方法,包括父类中继承的
Method publicMethod = c.getMethod("publicHello", String.class);

Method saySomething = c.getMethod("publicHello", String.class);
//获取所有方法 本方法中
Method thisClassMethod = c.getDeclaredMethod("privateHello", String.class);
//设置权限
thisClassMethod.setAccessible(true);
//不能直接转成类来执行 classloader 不同
publicMethod.invoke(c.newInstance(), "publicMethod");
saySomething.invoke(c.newInstance(), "saySomething");

thisClassMethod.invoke(c.newInstance(), "thisClassMethod");

}catch (Exception e) {
e.printStackTrace();
}
}
}