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

标签 java inheritance reflection

我知道有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/

相关文章:

typescript - 在 TypeScript 中扩展 DataView 会抛出 "Constructor DataView requires ' new'"

C++:可以继承类及其 protected 成员类型吗?

java - MongoDB 中的软删除过程

java - 如何比较字符串数组并计算相似单词

java - 多个dex文件定义<我的包>/BuildConfig,找不到原因 :

java - GCJ(GNU Compiler for Java)是发布 webapp 的可行工具吗?

.net - 为什么枚举派生自 System.Enum 并且同时是整数?

c# - Reflection.Emit:在 getter/setter 中调用函数的属性

java - 方面与实例方法中的类 getName() 行为

c# - 使用反射调用具有引用参数的方法