繁体   English   中英

使用JAVA反射执行类

[英]using JAVA reflection to execute the class

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

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

这是您要执行的操作的独立示例。

您正在运行的代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM