简体   繁体   English

在编译时强制存在无参数构造函数(Java)

[英]Enforce presence of no-argument constructor at compile time (Java)

I've got a class somewhat like this: 我的课程有点像这样:

public class Test {

    private final List<ISomeType> things = new LinkedList<ISomeType>();

    public <T extends ISomeType> Test(Class<T> clazz, int order) {
        for (int i = 0; i < order; i++) {
            try {
                this.things.add(clazz.newInstance());
            } catch (Exception e) { 
                // stackoverflowers use your imagination
            }
        }
    }
}

Where I expect and hope the Class clazz has an accessible no-argument constructor. 我期望的地方,并希望Class clazz有一个可访问的无参数构造函数。 Is there any way I can enforce presence of it at compile time? 有没有什么办法可以在编译时强制执行它?

There is no way to enforce constructor requirements at compile time. 在编译时无法强制执行构造函数要求。 At runtime you can check class.getConstructors() and ensure there is one that has no args (or just catch the exception like you are in the sample code). 在运行时,您可以检查class.getConstructors()并确保有一个没有args(或者只是像示例代码一样捕获异常)。

Usually the no-arg constructor requirement is just listed in the Javadoc of the base class or interface. 通常,no-arg构造函数要求只列在基类或接口的Javadoc中。

There are some tools for code style validation that can be extended to check for this type of requirement. 有一些代码样式验证工具可以扩展以检查这种类型的需求。 For eclipse (and others), PMD may help you. 对于日食(和其他人), PMD可能会帮助你。 By looking at the tutorial I think you should be able to write an specific rule to check for constructors without any parameters. 通过查看教程,我认为您应该能够编写一个特定的规则来检查没有任何参数的构造函数。

What about this? 那这个呢?

interface Provider<T> {
   T get();
}

public class Test {

    private final List<ISomeType> things = new LinkedList<ISomeType>();

    public <T extends ISomeType> Test(Provider<T> provider, int order) {
        for (int i = 0; i < order; i++) {
            try {
                this.things.add(provider.get());
            } catch (Exception e) { 
                // stackoverflowers use your imagination
            }
        }
    }
}

Your best bet is to create a unit test that checks this for each class you care about, and then run the unit tests at build time. 最好的办法是创建一个单元测试,为你关心的每个类检查这个,然后在构建时运行单元测试。 Alternately, you can create a test class -- not distributed with your code -- that does nothing but exercise the no-arg constructors of the classes you care about. 或者,您可以创建一个测试类 - 不与您的代码一起分发 - 除了运行您关注的类的无参数构造函数之外什么都不做。 Not a great option. 不是一个很好的选择。

The link below shows how to solve a similar situation (checking whether the subclasses of a particular class all have no-argument constructor) using Java 6 and the Annotation Processing Tool: 下面的链接显示了如何使用Java 6和注释处理工具解决类似情况(检查特定类的子类是否都具有无参数构造函数):

Annotation Processing Tool 注释处理工具

Maybe you can adapt their solution to solve your problem. 也许你可以调整他们的解决方案来解决你的问题。

Reflection is about doing things at runtime instead of compile time. 反思是关于在运行时而不是编译时做事。 Don't use reflection if you want your code to work. 如果您希望代码能够工作,请不要使用反射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无参构造函数调用2参数构造函数 - No-argument constructor calling 2-argument constructor Exception或其子类中的无参数构造函数 - No-argument constructor in Exception or its subclasses 隐式调用超类中的无参数构造函数 - Calling no-argument constructor in superclass implicitly 强制超类包含无参数构造函数 - Force superclasses to include a no-argument constructor Java无参数构造函数:抛出不可能的异常,或者有空的catch块? - Java no-argument constructor: Throw impossible exception, or have empty catch block? Java:在运行时在子类中不强制使用arg构造函数 - java: enforce no arg constructor in subclass at run time 为无参数构造函数的类创建动态代理 - Create a dynamic proxy for a class without no-argument constructor Firebase数据库:尽管存在错误,但仍出现“无参数构造函数”错误 - Firebase Database: Getting “No-Argument Constructor” Error Despite Having It Scala类的最终def this()声明没有公共的无参数构造函数 - Scala class final def this() declares no public no-argument constructor Android Firebase数据库异常:未定义无参数构造函数 - Android Firebase Database exception: not define a no-argument constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM