java中的泛型类型与通配符编译问题

时间:2017-10-04 19:01:51

标签: java generics intellij-idea wildcard

我在java中面临一个通用vs通配符问题。

class A<T> {
    T value;
}

class B<T> {
    T value;
}

public <T> A<? extends B<T>> methodA() {

    A<B<Object>> gg = fetchFromSomeLocation();
    return (A<? extends B<T>>) gg;
}

public <T, E extends B<T>> A<E> methodB() {

    A<B<Object>> gg = fetchFromSomeLocation();
    return (A<E>) gg;
}

所以methodB()编译很好,没问题。但是methodA导致编译失败:

incompatible types: A<B<java.lang.Object>> cannot be converted to A<? extends B<T>>

我无法理解为什么会这样。

关于Intellij的P.S它显示为精确有效的代码。

修改

显然这很好编译

public static <T> A<? extends B<T>> methodC() {

    A<B<Object>> gg = new A<>();
    return (A<? extends B<T>>)(A<?>) gg;
}

0 个答案:

没有答案