还有一个额外的“隐藏”参数,它是封闭类的实例。您需要使用构造函数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() {
// ...
}
}
}