我有一个通用接口,需要将其类型作为通用参数:
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
有没有一种方法可以声明此方法有效并且没有未经检查的类型?
java大神给出的解决方案
在Java 5+中,返回类型可以为covariant,因此您无需使用泛型,因此一开始您就有:
interface Base {
Base foo();
}
class Derived implements Base {
public Derived foo() { ... }
public Derived bar() { ... }
}
那么我就不会再看到泛型的问题了。
java:继承 - java有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…
Tomcat找不到直接放置在classes文件夹下的类 - java我有以下JSP:<%@ page import="foo.*" %> <html> <body> The page count is: <%=Counter.getCount()%> </body> </html> 我在包Counter中有一个foo类,该类存储在: …
无法在Maven surefire中运行多个执行? - java我想运行名称以ResourceTest.java结尾的测试类,因此我在执行后定义了它们。<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <co…
DataSourceTransactionManager和JndiObjectFactoryBean和JdbcTemplate的用途是什么? - java以下的用途是什么:org.springframework.jdbc.core.JdbcTemplate org.springframework.jdbc.datasource.DataSourceTransactionManager org.springframework.jndi.JndiObjectFactoryBean <tx:annotatio…
T是此代码中的类还是接口? - javaWhat is <? super T> syntax?我正在阅读此答案,这使我消除了一些疑问,但我不明白这一行中的一件事:T extends Comparable< ? super T>该帖子答复中的每个人都解释说T实现了Comparable<T or T's superclass>;但是有书面的扩展,所以T是C…