且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 6 与 Java 7 之间自动拆箱的差异

更新时间:2023-12-03 15:12:16

看起来像Java 5/6 JLS 中的同一部分,可能是为了阐明允许的转换.

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 说

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:

可以通过拆箱转换(第 5.1.8 节)将引用类型的值转换为原始类型.

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

Java 7 JLS 还包含一个表(表 5.1),其中包含从引用类型到原语的允许转换(该表不包含在 Java 5/6 JLS 中).这明确列出了从 Object 到基元的强制转换,作为带拆箱的缩小引用转换.

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.

原因在这封电子邮件中说明:

底线:如果规范.允许 (Object)(int) 它也必须允许 (int)(Object).

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