Does the Java ClassLoader load inner classes?

后端 未结 5 1599
迷失自我
迷失自我 2020-12-08 10:50

If I have a inner class declaration such as:

Class A {
    public static class B {
    }
}

followed by:

Class impl         


        
5条回答
  •  星月不相逢
    2020-12-08 11:10

    Inner classes i.e class B cannot exist outside the parent class. You need to construct the parent class i.e class A first.

    and if you remove static from your inner class i.e for non-static inner class , you need to pass the parent class in during construction of the inner class.

    Object a = Class.forName("A").newInstance();    //object of outer class
    
    //object of inner class
    Object b = implClass.getDeclaredConstructor(new Class[] { a.getClass() })
            .newInstance(new Object[] { a });
    

提交回复
热议问题