[英]List of recursive generic type
我有一個通用接口,需要將其類型作為通用參數:
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() { ... }
}
我有另一個類使用此接口作為通用參數。
interface Policy<B extends Base<B>> {
B apply(B b);
}
我有一些Policy
實現只適用於特定的派生類:
class DerivedPolicy implements Policy<Derived> {
public Derived apply(Derived d) {
return d.foo().bar();
}
}
但其他人可以使用任何實現
class GeneralPolicy implements Policy {
public Base apply(Base b) {
return b.foo();
}
}
上面的代碼編譯,但在GeneralPolicy
提供有關未經檢查的類型的警告,這是准確的,因為Base
沒有指定其泛型類型。 第一個明顯的修復是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
使用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
我做了最后一次嘗試: 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
有沒有辦法聲明這個有效並且沒有未經檢查的類型?
在Java 5+中,返回類型可以是協變的 ,因此您不需要使用泛型,一開始您有:
interface Base {
Base foo();
}
class Derived implements Base {
public Derived foo() { ... }
public Derived bar() { ... }
}
然后我再也看不到仿制葯的問題了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.