Inference variable has incompatible bounds. Java 8 Compiler Regression?

后端 未结 3 512
一个人的身影
一个人的身影 2020-12-31 00:56

The following program compiles in Java 7 and in Eclipse Mars RC2 for Java 8:

import java.util.List;

public class Test {

    static final void a(Class

        
3条回答
  •  旧巷少年郎
    2020-12-31 01:47

    Thanks to bayou.io’s answer we can narrow the problem to the fact that

    > void a(X instance) {
        b(instance);  // error
    }
    static final  List b(List list) {
        return list;
    }
    

    produces an error while

    > void a(X instance) {
        List instance2=instance;
        b(instance2);
    }
    static final  List b(List list) {
        return list;
    }
    

    can be compiled without problems. The assignment of instance2=instance is a widening conversion which should also happen for method invocation arguments. So the difference to the pattern of this answer is the additional subtype relationship.


    Note that while I’m not sure whether this specific case is in line with the Java Language Specification, some tests revealed that Eclipse accepting the code is likely due to the fact that it is more sloppy regarding Generic types in general, as the following, definitely incorrect, code could be compiled without any error nor warning:

    public static void main(String... arg) {
        List l1=Arrays.asList(0, 1, 2);
        List  l2=Arrays.asList("0", "1", "2");
        a(Arrays.asList(l1, l2));
    }
    static final void a(List> type) {
        test(type);
    }
    static final > void test(List type) {
        L l1=type.get(0), l2=type.get(1);
        l2.set(0, l1.get(0));
    }
    

提交回复
热议问题