Java 泛型 Eclipse 编译器错误?

问题描述 投票:0回答:1

我的问题是其他人问题的后续:无界通配符传递给方法

他很感兴趣为什么下面的代码会被编译:

public class ColTest {
    static<T> T wildSub(ArrayList<? extends T> holder, T arg){
        T t=holder.get(0);
        return t;
    }

    public static void main(String[] args) {
        ArrayList<?> list=new ArrayList<Long>(Arrays.asList(2L,3L,7L));
        Long lng=1L;
        ColTest.wildSub(list, lng);
    }
}

我们得出的结论是,技巧是编译器推断出 ?作为一个对象,并通过 Object->Long 的简单继承,使以下 Long 参数通过。

代码确实使用 Sun/Oracle javac 进行编译(我使用 1.6.0_26-b03),但无法在 Eclipse 中编译(我使用 Helios),它显示以下编译错误:

The method wildSub(ArrayList<? extends T>, T) in the type ColTest is not applicable for the arguments (ArrayList<capture#2-of ?>, Long)

我的问题是:

这是 Eclipse 使用的 Java 编译器实现中的错误,还是 Java“泛型推理算法”规范中的某种模糊性,该规范是有效的,只是 Eclipse 的实现方式不同?

java eclipse generics jvm
1个回答
4
投票

这似乎是 Eclipse 的错误。

T 应被推断为对象,根据 15.12.2.7。

15.12.2.8 还有一个包罗万象的子句:“任何尚未推断的剩余类型变量都将被推断为具有 Object 类型”

T=Object,根据 15.12.2.2,该方法适用

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12

© www.soinside.com 2019 - 2024. All rights reserved.