Java generics code compiles in eclipse but not in command line

后端 未结 4 1261
[愿得一人]
[愿得一人] 2020-12-21 08:51

I know there have been several questions in the past regarding things that compile in eclipse but not in command line, but I could not find an answer to my problem yet.

4条回答
  •  无人及你
    2020-12-21 09:39

    Very interesting question.

    The following code doesn't compile

        Integer x = null;
        String s = null;
        if(x==s){}   // error: incomparable types
    

    JLS3#15.21.3 [1] says

    A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5)

    Apparently the previous example looks like an obvious programming error, so the spec tries to catch it and alert the programmer. There wouldn't have been any trouble is Java wanted to allow it. The workaround for the example is to cast one side to Object.

    Back to your question, we need to decide if OtherEnum can be cast to T, or the other way around. This is a surprisingly difficult question; following the procedure of JLS3#5.5 [2], the answer is no.

    It comes down to whether OtherEnum can be cast to Enum; then we can find super types X=Enum and Y=Enum, which are provably distinct parameterized types. So cast is illegal.

    Well, such specification is too elaborate, who in their right minds would care?

    You can work around it by casting one to Object, say (Object)enumVal == OtherEnum.a

    Java 7 behaves differently, it does compile your code. I don't know the reason. It's possible that Java7 introduces a new bug. Or it has a new spec that allows the code (but we don't have access to the new spec). Another possibility is that I misunderstood the term "provably distinct parameterized types"; however without formal definition, it is intuitive that Enum and Enum are distinct.

    ref

    [1] http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.3

    [2] http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#20232

提交回复
热议问题