2017-02-27 30 views
0

我的情况是不同的,但作为一个例子如何限制普通类型的接口只接受实施者类

public interface Comparable<T> 

会允许我说:

public class MyType implements Comparable<OtherType> 

但这是很少你想要什么实现。

有没有办法来我说:

public class MyType implements Comparable<MyType> 

我得到的最接近是:

public interface Comparable<T extends Comparable<T>> 

这只能部分,因为它不会允许OtherType如果它本身不具有可比性,但会允许:

public class MyType implements Comparable<Integer> 

满足条件。

+5

无法在Java中完成。至少不是在编译时。 – shmosel

+2

也许如果你说为什么你需要在编译时执行这样的限制,我们可以拿出不同的设计。请参阅http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – SergGr

+0

@SergGr简单地减少运行时检查。该接口的默认方法会执行整个注释处理,并严格要求它们具有相同类型(或至少是一个子类型)。 – Mordechai

回答

2

这在Java中不可行。

请考虑是否可以要求类型参数Comparable与实现类相同。然后,如果你有一个class Foo implements Comparable<Foo>,然后class Bar extends Foo,Bar也将自动实现Comparable<Foo>通过继承在Java的作品。但是这违背了实现类与类型参数相同的约束,因为Bar未实现Comparable<Bar>(并且甚至不能明确地使Bar实现Comparable<Bar>,因为类不能实现具有两个不同类型参数的泛型类型)。

+0

关于违约的好处。 – Mordechai

相关问题