简体   繁体   English

你能编写一个需要Java中的无参数构造函数或工厂的接口吗?

[英]Can you write an interface that requires a no-arg constructor or factory in Java?

In Java, is there a way to enforce a constraint that any Class that implements an interface has a no-arg constructor? 在Java中,有没有办法强制实现一个实现接口的类具有no-arg构造函数的约束? If not can you enforce that it has a factory that returns an instance of the class? 如果没有,你能否强制它有一个返回该类实例的工厂?

In Java, is there a way to enforce a constraint that any Class that implements an interface has a no-arg constructor? 在Java中,有没有办法强制实现一个实现接口的类具有no-arg构造函数的约束?

Not at compile-time, no. 不是在编译时,不是。

If not can you enforce that it has a factory that returns an instance of the class? 如果没有,你能否强制它有一个返回该类实例的工厂?

Not at compile-time, no. 不是在编译时,不是。

Unit tests can check for both of these, of course, if you can work out the types to check. 当然,单元测试可以检查这两种情况,如果你可以计算出要检查的类型。

No, to both. 不,两者兼而有之。 In general, though, you should neither want or need to do that. 但是,一般而言,您既不想要也不需要这样做。

Not on the interface, but you can write a class with a factory method: 不在界面上,但您可以使用工厂方法编写类:

public abstract class Foo {

    private Foo() {}

    public static Bar createBar() {
        return new BarImpl();
    }

}

public interface Bar {}

Bar myBar = Foo.createBar();

That's how Java exposes their factory methods on classes like Calendar.java. 这就是Java在Calendar.java这样的类上公开其工厂方法的方式。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM