ZoeH
ZoeH

Reputation: 109

using JAVA reflection to execute the class

So, here is the class with private Inner class declared inside and a private attribute. I need to use Java reflection writing a test program in main function to execute this class.

public class Outter {
private Inner in;

public Outter(){
    in = new Inner();
}

private class Inner{
    private void test(){
        System.out.println("test");
    }
}

}

Here is test code: my questions are listed following the statement.

public class Test
{
    public static void main(String[] args) throws Exception
    {
        // 1. How do i create a Class type for Inner class since its modifier
        // is private, if I am going to need .setAccessible() then how do i
        // use it?
        Class outter1 = Outter.class; 

        // 2. How do I pass parameters of type Inner to the Class object?
        Constructor con = outter1.getConstructor(new Class[]{int.class});

        // 3. Like this?
        Field fields = outter1.getField("test");
        fields.setAccessible(true);

        // 4. Well I am lost what is the logic route for me to follow when
        // using java reflection to execute a class like this!
        Object temp = outter1.newInstance();
        Outter outter = (Outter)temp;
        System.out.println(fields.get(outter));
    }
}

Upvotes: 0

Views: 162

Answers (1)

Mena
Mena

Reputation: 48404

Here's a self-contained example of what you're trying to do.

Code you're running

try {
   // gets the "in" field
   Field f = Outer.class.getDeclaredField("in");
   // sets it accessible as it's private
   f.setAccessible(true);
   // gets an instance of the Inner class by getting the instance of the 
   // "in" field from an instance of the Outer class - we know "in" is
   // initialized in the no-args constructor
   Object o = Object o = f.get(Outer.class.newInstance());
   // gets the "execute" method
   Method m = o.getClass().getDeclaredMethod("test", (Class<?>[])null);
   // sets it accessible to this context
   m.setAccessible(true);
   // invokes the method
   m.invoke(o, (Object[])null);
}
// TODO better handling
catch (Throwable t) {
    t.printStackTrace();
}

Classes (inner/outer)...

public class Outer {
    private Inner in;
    public Outer() {
        in = new Inner();
    }
    private class Inner {
        private void test() {
            System.out.println("test");
        }
    }
}

Output

test

Upvotes: 2

Related Questions