我知道有no way to enforce this at compile time ,但我希望有一种方法可以在运行时使用反射来做到这一点。
最佳答案
您可以通过反射以显而易见的方式做到这一点:
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
仅返回公共(public)构造函数;要允许私有(private)构造函数,请使用 getDeclaredConstructor
)。
关于java:在运行时在子类中强制执行无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731536/