问题是您正在尝试实例化一个内部类,您只能在外部类的实例上访问它。内部类的构造函数采用封闭类的隐式隐藏instance
。通过分析这个简单类的字节码可以看出:
public class Demo {
class Test {
}
}
现在,编译代码:
javac Demo.java
这将创建两个类文件:
Demo.class
Demo$Test.class
运行以下命令查看 的字节码Demo$Test.class
:
javap -c . Demo$Test
您将得到以下结果:
class Demo$Test {
final Demo this$0;
Demo$Test(Demo);
Code:
0: aload_0
1: aload_1
2: putfield #1 // Field this$0:LDemo;
5: aload_0
6: invokespecial #2 // Method java/lang/Object."<init>":
()V
9: return
}
那么,你看到类的构造函数了吗?它Demo
作为参数。因此,没有 0-arg 构造函数。
但是,如果您创建内部类static
,它会起作用,因为这样您就不需要任何封闭类的实例来调用内部类构造函数。
使用static
内部类 - 替代方案:
public class AFactory {
public static int currentRange;
private static abstract class A {
protected final Object range = AFactory.currentRange;
}
public static class B extends A {
public int congreteRange = 42;
}
synchronized A createNew(Class<? extends B> clazz) throws Exception {
currentRange = clazz.newInstance().congreteRange;
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
AFactory factory = new AFactory();
System.out.println(factory.createNew(B.class).range);
}
}
使用非static
内部类 - 最终代码:
如果您不想制作它们static
,那么您必须首先创建封闭类的实例。并将其传递给内部类的构造函数。要获取内部类的构造函数,可以使用Class#getDeclaredConstructor
method。
现在,您必须修改您的工厂方法以采用Constructor
as 参数。像这样修改你的代码:
public class AFactory {
public int currentRange;
private abstract class A {
protected final Object range = currentRange;
}
public class B extends A {
public int congreteRange = 42;
}
synchronized A createNew(Constructor<? extends A> ctor) throws Exception {
// Pass `this` as argument to constructor.
// `this` is reference to current enclosing instance
return ctor.newInstance(this);
}
public static void main(String[] args) throws Exception {
AFactory factory = new AFactory();
// Get constructor of the class with `AFactory` as parameter
Class<B> bClazz = B.class;
Constructor<B> ctor = bClazz.getDeclaredConstructor(AFactory.class);
System.out.println(factory.createNew(ctor));
}
}