我有一个通用接口,需要将其类型作为通用参数:
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<?>>>
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
有没有办法声明这个有效并且没有未经检查的类型?
答案 0 :(得分:0)
在Java 5+中,返回类型可以是https://cors-anywhere.herokuapp.com/,所以你不需要使用泛型,一开始就有:
interface Base {
Base foo();
}
class Derived implements Base {
public Derived foo() { ... }
public Derived bar() { ... }
}
然后我再也看不到仿制药的问题了。