Java: How to load a class (and its inner classes) that is already on the class path?

后端 未结 3 1233
我在风中等你
我在风中等你 2020-12-19 06:45

How can I load a class that is already on the class path, instantiate it, and also instantiate any inner classes defined within it?

EG:

public class          


        
3条回答
  •  臣服心动
    2020-12-19 07:29

    Inner classes cannot exist outside the parent class. You need to construct the parent class first. Without reflection this would look like:

    InnerClass innerClass = new TestClass().new InnerClass();
    

    In reflection, you need to pass the parent class in during construction of the inner class.

    Object testClass = Class.forName("com.example.TestClass").newInstance();
    for (Class cls : testClass.getClass().getDeclaredClasses()) {
        // You would like to exclude static nested classes 
        // since they require another approach.
        if (!Modifier.isStatic(cls.getModifiers())) {
            Object innerClass = cls
                .getDeclaredConstructor(new Class[] { testClass.getClass() })
                .newInstance(new Object[] { testClass });
        }
    }
    

提交回复
热议问题