简体   繁体   English

当方法的参数为List时如何通过反射调用私有方法?

[英]How to invoke private method via Reflection when parameter of method is List?

How can I invoke private method via Reflection API?如何通过反射 API 调用私有方法?

My code我的代码

public class A {
    private String method(List<Integer> params){
        return "abc";
    }
}

And test并测试

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);
    }
}

There are two problems in your code你的代码有两个问题

  • you are using getMethod which can only return public methods, to get private ones use getDeclaredMethod on type which declares it.您正在使用只能返回public方法的getMethod ,要获取私有方法,请在声明它的类型上使用getDeclaredMethod
  • you are invoking your method on "method" String literal instead of instance of A class (String doesn't have this method, so you can't invoke it on its instance. For now your code is equivalent to something like "method".method(yourList) which is not correct).您正在"method"字符串文字而不是A类的实例上调用您的方法(字符串没有此方法,因此您不能在其实例上调用它。现在您的代码相当于"method".method(yourList)不正确)。

Your code should look like您的代码应如下所示

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>());
//                               ^^^^^^^ 

//OR pass already existing instance of A class
//A myA = new A(); //other instance of A on which you want to call the method
//...
//String res = (String) met.invoke(myA, new ArrayList<Integer>());

System.out.println(res);

You can do it in this way if you need to create an Instance of the A by reflection too如果您也需要通过反射创建A的实例,您可以这样做

 public static void main(String[] args) throws Exception {
    Class<?> aClass = A.class;
    Constructor<?> constructor = aClass.getConstructors()[0];
    Object a = constructor.newInstance(); // create instance of a by reflection
    Method method = a.getClass().getDeclaredMethod("method", List.class); // getDeclaredMethod for private
    method.setAccessible(true); // to enable accessing private method
    String result = (String) method.invoke(a, new ArrayList<Integer>());
    System.out.println(result);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM