我有一个关于在 Java 中提升基本类型的问题。正如我们在下面的例子中看到的,其中一个方法由于类型不匹配的错误而没有编译。每个方法返回相同的值,但类型不同。
原始 long
方法的版本工作正常,而包装类 Long
的版本失败。这是因为 return
语句中的 int
文字将首先提升为更广泛的原始类型(例如 long
),然后再提升为相应的包装器类 Integer
等等。由于 Integer
不是 Long
的子类,因此编译器会报错。
但是为什么包装类 Byte
的版本没有任何错误?此时编译器究竟做了什么?
long getPrimitiveLong() {
return 12; // valid
}
Long getWrapperLong() {
return 12; // Error: type mismatch
}
Byte getWrapperByte() {
return 12; // valid
}
最佳答案
带有 Byte
的版本通过一些编译器魔法工作。
不像 long
数字文字可以用 L
后缀构造,例如12L
,没有byte
文字这样的东西。这就是为什么 Java 编译器将适合字节的数字文字视为 byte
文字的原因。因此,上一个示例中的 12
被视为 byte
类型的常量。
Java Language Specification在第 5.2 节中提供了对此转换的描述:
A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
Byte
and the value of the constant expression is representable in the typebyte
.Short
and the value of the constant expression is representable in the typeshort
.Character
and the value of the constant expression is representable in the typechar
.
关于java - 促进原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46933168/