java - 促进原始类型

标签 java types casting wrapper primitive

我有一个关于在 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 type byte.
  • Short and the value of the constant expression is representable in the type short.
  • Character and the value of the constant expression is representable in the type char.

关于java - 促进原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46933168/

相关文章:

java - 比 double 更精确的数字数据类型?

java - Java编译器错误中的动态转换

Java JPA 防止代理调用 db

java - 具有多个 p 的行选择 :dataTable

list - 在 Dart 中,List.from 和 .of、Map.from 和 .of 之间有什么区别?

Java 将 Image 转换为 BufferedImage

c# - MultiBinding - 指定的转换无效

java - Jetty 是否可以配置为提供 AWS Certificate Manager 证书?

java - 如何通过彩信从 Android 应用程序发送图片?

java - 我认为你不能在数组中混合类型(Java)