Java generics code compiles with javac, fails with Eclipse Helios

后端 未结 8 1645
挽巷
挽巷 2020-12-16 02:53

I have the following test class that uses generics to overload a method. It works when compiled with javac and fails to compile in Eclipse Helios. My java version is 1.6.0_2

8条回答
  •  悲哀的现实
    2020-12-16 03:50

    This code is correct, as described in JLS 15.12.2.5 Choosing the Most Specific Method.

    Also, consider coding to the interface:

    List ss = new ArrayList();
    List is = new ArrayList();
    // etc.
    

    As @McDowell notes, the modified method signatures appear in the class file:

    $ javap build/classes/Test
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        public Test();
        public static void main(java.lang.String[]);
        public java.lang.String getFirst(java.util.ArrayList);
        public java.lang.Integer getFirst(java.util.ArrayList);
    }
    

    Note that this does not contradict @meriton's observation about the class file. For example, the output of this fragment

    Method[] methods = Test.class.getDeclaredMethods();
    for (Method m : methods) {
        System.out.println(Arrays.toString(m.getGenericParameterTypes()));
    }
    

    shows the formal parameter of main(), as well as the two generic type parameters:

    [class [Ljava.lang.String;]
    [java.util.ArrayList]
    [java.util.ArrayList]
    

提交回复
热议问题