mercredi 26 septembre 2018

Invoke Inner class method having parameters using reflection java

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?





Aucun commentaire:

Enregistrer un commentaire