我有一个通用接口,需要将其类型作为通用参数:
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);
}
我有一些只能与特定派生类一起使用的策略
实现:
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实现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实现了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
有没有一种方法可以声明它,既能正常工作又不会有未检查的类型?