![](/img/trans.png)
[英]Get Instance should return object of type implementor class or of type interface
[英]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 Foo
, Bar
也将通过Java中继承的方式自动实现Comparable<Foo>
。 但这会违反实现类与类型参数相同的约束,因为Bar
不实现Comparable<Bar>
(而且您甚至不能显式让Bar
实现Comparable<Bar>
,因为类不能实现泛型类型(带有两个不同的类型参数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.