Differences in auto-unboxing between Java 6 vs Java 7

后端 未结 2 799

I have noted a difference in auto unboxing behavior between Java SE 6 and Java SE 7. I\'m wondering why that is, because I can\'t find any documentation of changes in this b

相关标签:
2条回答
  • 2020-11-30 19:43

    You are right; to put it more simply:

    Object o = new Integer(1234);
    int x = (int) o;
    

    This works in Java 7, but gives a compilation error in Java 6 and below. Strangely, this feature is not prominently documented; for example, it's not mentioned here. It's debatable if it's a new feature or a bug fix (or a new bug?), see some related info and discussion. The consensus seems to point to an ambiguity in the original spec, which led to a slightly incorrect/inconsistent implementation on Java 5/6, which was fixed in 7, because it was critical for implementation of JSR 292 (Dynamically Typed Languages).

    Java autoboxing has now some more traps and surprises. For example

    Object obj = new Integer(1234);
    long x = (long)obj;
    

    will compile, but fail (with ClassCastException) at runtime. This, instead, will work:

    long x = (long)(int)obj;

    0 讨论(0)
  • 2020-11-30 19:49

    It looks like the language in section 5.5 Casting Conversion of Java 7 JLS was updated in comparison to the same section in the Java 5/6 JLS, probably to clarify the allowed conversions.

    Java 7 JLS says

    An expression of a reference type may undergo casting conversion to a primitive type without error, by unboxing conversion.

    Java 5/6:

    A value of a reference type can be cast to a primitive type by unboxing conversion (§5.1.8).

    The Java 7 JLS also contains a table (table 5.1) of allowed conversions (this table is not included in the Java 5/6 JLS) from reference types to primitives. This explicitly lists casts from Object to primitives as a narrowing reference conversion with unboxing.

    The reason is explained in this email:

    Bottom line: If the spec. allows (Object)(int) it must also be allowing (int)(Object).

    0 讨论(0)
提交回复
热议问题