Search code examples
javareflectionclassloader

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


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 TestClass {


    public class InnerClass { }

}

Solution

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