[英]List of recursive generic type
I have a generic interface which needs to be have its type as a generic parameter: 我有一个通用接口,需要将其类型作为通用参数:
interface Base<X extends Base<X>> {
X foo();
}
class Derived implements Base<Derived> {
public Derived foo() { ... }
public Derived bar() { ... }
}
class Derived2 implements Base<Derived2> {
public Derived2 foo() { ... }
public void quz() { ... }
}
I have another class which uses this interface as a generic parameter. 我有另一个类使用此接口作为通用参数。
interface Policy<B extends Base<B>> {
B apply(B b);
}
I have some Policy
implementations that only work with a specific derived class: 我有一些
Policy
实现只适用于特定的派生类:
class DerivedPolicy implements Policy<Derived> {
public Derived apply(Derived d) {
return d.foo().bar();
}
}
but others that can work with any implementation 但其他人可以使用任何实现
class GeneralPolicy implements Policy {
public Base apply(Base b) {
return b.foo();
}
}
The above code compiles, but gives warnings about unchecked types in GeneralPolicy
, which is accurate since Base
does not have its generic type specified. 上面的代码编译,但在
GeneralPolicy
提供有关未经检查的类型的警告,这是准确的,因为Base
没有指定其泛型类型。 The first obvious fix is GeneralPolicy implements Policy<Base>
, w 第一个明显的修复是
GeneralPolicy implements Policy<Base>
,w
Test.java:26: error: type argument Base is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base> {
^
where B is a type-variable:
B extends Base<B> declared in interface Policy
Using GeneralPolicy implements Policy<Base<?>>
also does not work: 使用
GeneralPolicy implements Policy<Base<?>>
也不起作用:
Test.java:26: error: type argument Base<?> is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base<?>> {
^
where B is a type-variable:
B extends Base<B> declared in interface Policy
I made one last try: GeneralPolicy implements Policy<Base<? extends Base<?>>>
我做了最后一次尝试:
GeneralPolicy implements Policy<Base<? extends Base<?>>>
GeneralPolicy implements Policy<Base<? extends Base<?>>>
Test.java:26: error: type argument Base<? extends Base<?>> is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base<? extends Base<?->- {
^
where B is a type-variable:
B extends Base<B> declared in interface Policy
Is there a way to declare this that works and does not have unchecked types? 有没有办法声明这个有效并且没有未经检查的类型?
In Java 5+ return type could be covariant , so you don't need to use generics, at the beginning you have: 在Java 5+中,返回类型可以是协变的 ,因此您不需要使用泛型,一开始您有:
interface Base {
Base foo();
}
class Derived implements Base {
public Derived foo() { ... }
public Derived bar() { ... }
}
then I don't see a problem with generics anymore. 然后我再也看不到仿制药的问题了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.