Alex
Alex

Reputation: 2179

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

How can I invoke private method via Reflection 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);
    }
}

Upvotes: 8

Views: 14794

Answers (2)

Pshemo
Pshemo

Reputation: 124275

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.
  • 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).

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 someA = new A(); // instance of A on which you want to call the method
// ╰╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╮
String res = (String) met.invoke(someA, new ArrayList<Integer>());

System.out.println(res);

Upvotes: 18

Ahmad Al-Kurdi
Ahmad Al-Kurdi

Reputation: 2305

You can do it in this way if you need to create an Instance of the A by reflection too

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

Upvotes: 3

Related Questions