java - 将泛型参数传递给方法时,Java 编译器生成不兼容错误
问题描述
我有这样的类结构:
public interface MyInterface {
}
public interface MyTypeIfc {
}
public class TypeOf<T extends MyTypeIfc> {
}
public class BaseType<T> {
public void write(String fieldName, T value) {
System.out.println(fieldName + value.toString());
}
}
public class MyTypeClass<T extends MyTypeIfc> extends BaseType<TypeOf<T>> {
public void write(TypeOf<T> value) {
System.out.println(value.toString());
}
}
public class Main {
private static final MyTypeClass<? extends MyInterface> myType = new MyTypeClass<>();
public static void main(String[] args) {
Main main = new Main();
main.start();
}
private void start() {
myType.write("fieldName", getNodeType()); <-- This line gives incompatible error
}
private TypeOf<? extends MyInterface> getNodeType() {
return null;
}
}
对于上面标记的行,我收到一个不兼容的错误:
Compilation failure
[ERROR] ....Main.java:[12,46] incompatible types: com.type.TypeOf<capture#1 of ? extends com.type.MyInterface> cannot be converted to com.type.TypeOf<capture#2 of ? extends com.type.MyInterface>
似乎 Java 不允许我将TypeOf<? extends MyInterface>
object 作为参数传递给接受TypeOf<? extends MyInterface>
.
有人可以帮我理解为什么吗?
解决方案
推荐阅读
- sql-server - 基于字段创建日期范围
- javascript - Angular5服务不发送数据?
- hyperledger-fabric - 是否有可能有一个带有 Hyperledger 的轻节点?
- javascript - 您如何解决 scrutinizer-ci 中的代码复杂性限制?
- youtube-api - 传递“publishedBefore”、“publishedAfter”和“nextPageToken”参数时,YouTube 数据 API v3 未返回任何结果
- matlab - 分箱 1:9 -> 等号元胞数组的分箱
- google-apps-script - 脚本延迟 - 等待配额
- javascript - 粘性侧边栏手风琴不会正确滚动
- javascript - JavaScript:XMLHttpRequest 状态总是返回 0
- c# - 无法执行操作,因为运行空间未处于“打开”状态。运行空间的当前状态是“破碎”