簡體   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