java 泛型 递归类型限制_递归泛型类型列表 - java

我有一个通用接口,需要将其类型作为通用参数:

interface Base> {

X foo();

}

class Derived implements Base {

public Derived foo() { ... }

public Derived bar() { ... }

}

class Derived2 implements Base {

public Derived2 foo() { ... }

public void quz() { ... }

}

我还有另一个使用此接口作为通用参数的类。

interface Policy> {

B apply(B b);

}

我有一些Policy实现仅适用于特定的派生类:

class DerivedPolicy implements Policy {

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,w

Test.java:26: error: type argument Base is not within bounds of type-variable B

class GeneralPolicy implements Policy {

^

where B is a type-variable:

B extends Base declared in interface Policy

使用GeneralPolicy implements Policy>也不起作用:

Test.java:26: error: type argument Base> is not within bounds of type-variable B

class GeneralPolicy implements Policy> {

^

where B is a type-variable:

B extends Base declared in interface Policy

我最后尝试了:GeneralPolicy implements Policy>>

Test.java:26: error: type argument Base extends Base>> is not within bounds of type-variable B

class GeneralPolicy implements Policy- {

^

where B is a type-variable:

B extends Base 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:

The page count is: 我在包Counter中有一个foo类,该类存储在: …无法在Maven surefire中运行多个执行? - java

我想运行名称以ResourceTest.java结尾的测试类,因此我在执行后定义了它们。org.apache.maven.pluginsmaven-surefire-plugin

以下的用途是什么:org.springframework.jdbc.core.JdbcTemplate org.springframework.jdbc.datasource.DataSourceTransactionManager org.springframework.jndi.JndiObjectFactoryBean

What is super T> syntax?我正在阅读此答案,这使我消除了一些疑问,但我不明白这一行中的一件事:T extends Comparable< ? super T>该帖子答复中的每个人都解释说T实现了Comparable;但是有书面的扩展,所以T是C…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值