Instantiate private inner class with java reflection

后端 未结 3 608
忘了有多久
忘了有多久 2020-11-29 04:09

Is it possible to instantiate a private inner class from another class using Java reflection. For example if I took this code

public class Main {
    public         


        
3条回答
  •  情话喂你
    2020-11-29 04:47

    You can do the following :

    public static void main(String[] args) throws Exception {
        // to get first class in OtherClass
        Class innerClass = OtherClass.class.getDeclaredClasses()[0];
        // getDeclaredConstructors for private constructor
        Constructor constructor = innerClass.getDeclaredConstructors()[0];
        // to enable accessing private constructor
        constructor.setAccessible(true);
        OtherClass outerObject = new OtherClass();
        //// create instance of Test by reflection
        Object o = constructor.newInstance(outerObject);
        System.out.println(o);
    }
    

提交回复
热议问题