Invoke Inner class method having parameters using reflection

Shree :

I am trying to test my code though knowing using reflection is not a good way of testing. I have a outer class as public having private inner class with a public method as below,

public class Outer {

    private class Inner {
        private int var = 1;

        public Inner(int a) {
            System.out.println("___");
        }

        public void test(int a) {
            System.out.println("Hey");
        }
    }
}

My main java class looks like below

main() {
    Outer b = new Outer();
    System.out.println(b);
    Class<?> innerClass = Class.forName("car.Outer$Inner");

    Constructor<?> constructor = innerClass.getDeclaredConstructor(Outer.class, 1);

    constructor.setAccessible(true);
    Object c = constructor.newInstance(b,b);

    Method method = c.getClass().getDeclaredMethod("test");
    method.setAccessible(true);
    method.invoke(c, 1);
}

This is throwing

Exception in thread "main" java.lang.NoSuchMethodException: car.Outer$Inner.test() at java.lang.Class.getDeclaredMethod(Class.java:2130) at car.A.main(A.java:36)

How to invoke inner class method taking parameter using reflection?

Ted Hopp :

You need to supply the argument class(es) in the call to getDeclaredMethod(). When you call getDeclaredMethod(), the first argument is the name of the method you want looked up and any remaining arguments are the classes of the argument(s) to the method you want. This is how getDeclaredMethod() distinguishes between overloaded method names to get one particular method. Since you have supplied no additional arguments, getDeclaredMethod() is looking for a method named test that takes no arguments. You're getting an exception because you have no such method in class Outer$Inner. The only test method you do have takes an int parameter`, so the following should do what you want:

Method method = c.getClass().getDeclaredMethod("test", int.class);

Here, int.class is the Class object corresponding to the primitive argument type int.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107814&siteId=1