繁体   English   中英

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

[英]How to restrict generic type of interface to accept only implementor class

我的情况不同,但作为示例

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>

因为它符合条件。

在Java中这是不可能的。

考虑是否有可能要求Comparable的类型参数与实现类相同。 然后,如果您有一个class Foo implements Comparable<Foo> ,然后还有一个class Bar extends FooBar也将通过Java中继承的方式自动实现Comparable<Foo> 但这会违反实现类与类型参数相同的约束,因为Bar不实现Comparable<Bar> (而且您甚至不能显式让Bar实现Comparable<Bar> ,因为类不能实现泛型类型(带有两个不同的类型参数)。

暂无
暂无

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

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