java:在运行时强制执行子类中的arg构造函数

时间:2016-04-20 00:04:53

标签: java inheritance reflection

我知道有no way to enforce this at compile time,但我希望有一种方法可以在运行时使用反射来实现这一点。

1 个答案:

答案 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)。