如何通过Reflection API调用私有方法?
我的代码
public class A {
private String method(List<Integer> params){
return "abc";
}
}
Run Code Online (Sandbox Code Playgroud)
并测试
public class B {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<A> clazz = A.class;
Method met = clazz.getMethod("method", List.class);
met.setAccessible(true);
String res = (String) met.invoke("method", new ArrayList<Integer>());
System.out.println(res);
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码中存在两个问题
getMethod哪些只能返回public方法,让私人使用getDeclaredMethod "method"文字而不是A类的实例上调用你的方法(String没有这个方法,所以你不能在它的实例上调用它 - 这"method".method(yourList)是不正确的).你的代码应该是这样的
Class<A> clazz = A.class;
Method met = clazz.getDeclaredMethod("method", List.class);
// ^^^^^^^^
met.setAccessible(true);
String res = (String) met.invoke(new A(), new ArrayList<Integer>());
// ^^^^^^^
System.out.println(res);
Run Code Online (Sandbox Code Playgroud)