使用JAVA反射来执行该类

时间:2014-06-24 13:07:21

标签: java reflection

因此,这里是在内部声明私有内部类的类和私有属性。 我需要使用Java反射在main函数中编写测试程序来执行这个类。

public class Outter {
private Inner in;

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

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

}

这是测试代码: 我的问题列在声明之后。

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

1 个答案:

答案 0 :(得分:2)

以下是您要做的事情的一个独立示例。

您正在运行的代码

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

课程(内部/外部)......

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

<强>输出

test