Java generics code compiles with javac, fails with Eclipse Helios

后端 未结 8 1627
挽巷
挽巷 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:47

    After some research, I have the answer:

    The code, as it is specified above should NOT compile. ArrayList<String> and ArrayList<Integer>, at runtime is still ArrayList. But your code is not working because the returning type. If you set the same returning types for both methods, javac won't compile that...

    I read that there is a bug in Java 1.6 (that is already fixed in Java 1.7) about this error. Is all about returning types... so, you will need to change the signature of your methods.

    There is the bug 6182950 in Oracle's Bug Database.

    0 讨论(0)
  • 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<String> ss = new ArrayList<String>();
    List<Integer> is = new ArrayList<Integer>();
    // 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.lang.String>]
    [java.util.ArrayList<java.lang.Integer>]
    
    0 讨论(0)
提交回复
热议问题