Java:JLS第5.2节赋值转换

标签 java type-conversion implicit-conversion

这是我之前问题的后续(我没有得到任何答复)。就这样吧。

如果我严格遵守 JLS 第 5.2 节中规定的规则,下面的操作应该会失败。

Byte b = 2;

它应该会失败,因为这里正在进行 2 次转换。首先是从 int 到 byte 的隐式收缩转换以及从 byte 到 Byte 的自动装箱转换。它在这里执行 2 次转换。

那为什么没有失败呢?

JLS第5.2节规定的规则不允许此处进行2次转换。

最佳答案

这是来自 same JLS Section 的引用:

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.

这显然适用于此。

关于Java:JLS第5.2节赋值转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18211732/

相关文章:

c++ - 从 int 到 vector 的隐式转换?

java - 为什么这个 while 循环没有终止?比较整数

c# - 最有效的 Dictionary<K,V>.ToString() 格式?

java - 在 JOptionPane JPasswordField 中设置焦点

c# - 如何从 double 转换为 Int64

c# - 带有 IConvertible 错误的 SqlParameter.Value 的隐式运算符和赋值

c++ - 重载转换运算符的后果

python - 为什么调用 Python 的 'magic method' 不像对应的运算符那样进行类型转换?

java - 如何使用 Spring Data Rest 在 GET 调用中获取自引用对象

java - 网络应用程序 : safetly update a shared List/Map in the AppContext