我知道有no way to enforce this at compile time,但我希望有一种方法可以在运行时使用反射来实现这一点。
答案 0 :(得分:2)
你可以通过反思明显地做到这一点:
public class Superclass {
public Superclass() {
try {
// get the constructor with no arguments
this.getClass().getConstructor();
} catch(ReflectiveOperationException e) {
throw new RuntimeException("Subclass doesn't have a no-argument constructor, or the constructor is not accessible", e);
}
}
}
(请注意,getConstructor
只会返回构造函数(如果它是公共的);要允许私有构造函数,请使用getDeclaredConstructor
)。