如何限制泛型类型的接口只接受实现者类

时间:2017-02-27 20:23:30

标签: java generics

我的情况不同,但作为一个例子

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>

因为它符合条件。

1 个答案:

答案 0 :(得分:2)

这在Java中是不可能的。

考虑是否可以要求Comparable的类型参数与实现类相同。然后,如果您有class Foo implements Comparable<Foo>,然后还有class Bar extends FooBar也会通过Java中的继承工作方式自动实现Comparable<Foo>。但这会违反实现类与类型参数相同的约束,因为Bar没有实现Comparable<Bar>(并且您甚至无法明确地Bar实现{ {1}},因为类不能实现具有两个不同类型参数的泛型类型。)