【发布时间】:2018-11-23 08:26:58
【问题描述】:
我有一个接口,其方法返回一个带有有界通配符的不可变集合。
public interface Foo {
Set<? extends Bar> getAllBar();
}
public interface Bar {
String getBar();
}
一个实现该接口的抽象类以及几个在不覆盖方法的情况下扩展它的具体类:
abstract class AbstractFoo implements Foo {
public Set<? extends Bar> getAllBar() {
return Collections.emptySet();
}
}
以及一个扩展抽象类的具体类,覆盖getAllBar,缩小通配符:
public class FooImpl extends AbstractFoo {
public Set<BarImpl> getAllBar() {
return Collections.singleton(new BarImpl());
}
}
public class BarImpl implements Bar {
public String getBar() {
return "Bar";
}
/**
* additional BarImpl method
*/
public boolean isWee() {
return true;
}
}
调用代码通常会将返回的集合的项作为 Bar 进行迭代,但一些调用类,知道 FooImpl 期望 BarImpl 的集合能够调用 isWee()。
class Zap {
private FooImpl foo;
boolean hasAnyWee() {
return foo.getAllBar().stream().anyMatch(BarImpl::isWee);
}
}
当然,现在 SonarQube 抱怨返回类型中的通配符 (https://jira.sonarsource.com/browse/RSPEC-1452)
但在我的情况下有那么错吗?
我怎么可能避免这种情况?
【问题讨论】:
标签: java return-type bounded-wildcard