How to instantiate an inner class with reflection in Java?
There's an extra "hidden" parameter, which is the instance of the enclosing class. You'll need to get at the constructor using Class.getDeclaredConstructor
and then supply an instance of the enclosing class as an argument. For example:
// All exception handling omitted!
Class<?> enclosingClass = Class.forName("com.mycompany.Mother");
Object enclosingInstance = enclosingClass.newInstance();
Class<?> innerClass = Class.forName("com.mycompany.Mother$Child");
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);
Object innerInstance = ctor.newInstance(enclosingInstance);
EDIT: Alternatively, if the nested class doesn't actually need to refer to an enclosing instance, make it a nested static class instead:
public class Mother {
public static class Child {
public void doStuff() {
// ...
}
}
}