首页 > 解决方案 > 将泛型参数传递给方法时,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>.

有人可以帮我理解为什么吗?

标签: java

解决方案


推荐阅读