[英]Enforce presence of no-argument constructor at compile time (Java)
我的课程有点像这样:
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
}
}
}
}
我期望的地方,并希望Class clazz有一个可访问的无参数构造函数。 有没有什么办法可以在编译时强制执行它?
在编译时无法强制执行构造函数要求。 在运行时,您可以检查class.getConstructors()并确保有一个没有args(或者只是像示例代码一样捕获异常)。
通常,no-arg构造函数要求只列在基类或接口的Javadoc中。
有一些代码样式验证工具可以扩展以检查这种类型的需求。 对于日食(和其他人), PMD可能会帮助你。 通过查看教程,我认为您应该能够编写一个特定的规则来检查没有任何参数的构造函数。
那这个呢?
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
}
}
}
}
最好的办法是创建一个单元测试,为你关心的每个类检查这个,然后在构建时运行单元测试。 或者,您可以创建一个测试类 - 不与您的代码一起分发 - 除了运行您关注的类的无参数构造函数之外什么都不做。 不是一个很好的选择。
反思是关于在运行时而不是编译时做事。 如果您希望代码能够工作,请不要使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.