这是我之前问题的后续(我没有得到任何答复)。就这样吧。
如果我严格遵守 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/