2 回答

TA贡献1827条经验 获得超4个赞
还有一个额外的“隐藏”参数,它是封闭类的实例。您需要使用构造函数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() {
// ...
}
}
}

TA贡献1865条经验 获得超7个赞
此代码创建内部类实例。
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});
添加回答
举报