I try to instantiate the inner class defined in the following Java code:
public class Mother {
public class Child {
public void doStuff() {
// ...
}
}
}
When I try to get an instance of Child like this
Class<?> clazz= Class.forName("com.mycompany.Mother$Child");
Child c = clazz.newInstance();
I get this exception:
java.lang.InstantiationException: com.mycompany.Mother$Child
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
...
What am I missing ?
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:EDIT: Alternatively, if the nested class doesn't actually need to refer to an enclosing instance, make it a nested static class instead:
This code create inner class instance.