我尝试实例化以下Java代码中定义的内部类:
public class Mother {
public class Child {
public void doStuff() {
// ...
}
}
}
当我试图获得像这样的儿童的实例
Class<?> clazz= Class.forName("com.mycompany.Mother$Child");
Child c = clazz.newInstance();
我得到这个例外:
java.lang.InstantiationException: com.mycompany.Mother$Child
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
...
我错过了什么?
有一个额外的"隐藏的";参数,它是封闭类的实例。您需要使用Class.getDeclaredConstructor
获取构造函数,然后提供封闭类的实例作为参数。例如:
// 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);
或者,如果嵌套类实际上不需要引用封闭实例,则将其改为嵌套的静态类:
public class Mother {
public static class Child {
public void doStuff() {
// ...
}
}
}
此代码创建内部类实例。
Class childClass = Child.class;
String motherClassName = childClass.getCanonicalName().subSequence(0, childClass.getCanonicalName().length() - childClass.getSimpleName().length() - 1).toString();
Class motherClassType = Class.forName(motherClassName) ;
Mother mother = motherClassType.newInstance()
Child child = childClass.getConstructor(new Class[]{motherClassType}).newInstance(new Object[]{mother});