java - 泛型返回类型方法中的不兼容类型 (Java)
问题描述
从 C++ 到 Java 的新手。具有通用返回类型的方法将无法编译。我认为这是因为我没有指定泛型方法的类型,但我什至不知道该怎么做。下面的代码不编译说:error: incompatible types: AnInterface cannot be converted to I ... where I is a type-variable:
在我看来,类型I
肯定看起来与返回类型兼容,get
因为我明确声明I
要扩展AnInterface
。
import java.util.*;
interface AnInterface {
public int aMethod();
}
class AClass implements AnInterface {
AClass() { l = new ArrayList<>(); }
public int aMethod() { return 1; }
public void add(AnInterface x) { l.add(x); }
public AnInterface get() { return l.get(0); }
// method on() will not compile
public <I extends AnInterface> I on(int x) { I i = get(); return i; }
List<AnInterface> l;
}
class BClass implements AnInterface {
public int aMethod() { return 2; }
}
class Main
{
public static void main(String[] args)
{
AClass a = new AClass();
BClass b = new BClass();
a.add(b);
// How do I even call AClass::on()
// BClass x = a.on<BClass>(); // I expect to call on() like this
}
}
解决方案
仔细看看方法on
:
public <I extends AnInterface> I on() {
I i = get();
return i;
}
I = BClass
用手段调用它get()
必须返回一个BClass
. get
但是is的签名public AnInterface get()
,意味着我们只知道它返回一个AnInterface
实现。它可以是BClass
,但也可以是其他任何实现AnInterface
。
你可以on
这样改变:
public AnInterface I on() {
AnInterface i = get();
return i;
}
签名现在显示on
返回的东西正在实现AnInterface
,这与我们从中返回的类型一致get
。
实际上,您的示例已经清楚地说明了为什么您发布的代码无法进行类型检查。
AClass a = new AClass();
AClass b = new AClass();
a.add(b);
BClass c = a.<BClass>on();
我们希望调用on
返回实例b
,因为这是添加到的第一个元素a
。但是b
是类型AClass
,不是BClass
。如果编译器不拒绝该程序,我们将在typeAClass
的变量中有一个 的实例。c
BClass
推荐阅读
- css - 使用 renderPlot() 删除 R Shiny ggplot 中 geom_sf() 对象周围的白边距
- javascript - React Native 版本不匹配。无法在 Android Studio 中生成构建,但通过 VS 代码 react-native run-android 正常运行
- wordpress - 在 Wordpress 中,如何为主题创建的帖子类型添加分类?
- shell - 如何将大 shell 脚本拆分或组织成小脚本并在主脚本中调用它?
- go - 当结构包含字符串时解码二进制数据
- javascript - CSS/jQuery 性能 - 提供更高分辨率的选择器是否更好
- redis - Redis Sentinel 具有 2 个应用服务器和 1 个额外的 Sentinel 节点设置
- bash - 我正在比较的一个或两个字符串值有问题吗?
- linux - 如何运行除选定行之外的 bash 脚本?
- python - 正则表达式模式只匹配到一半