为什么在自动装箱期间发生 final long 到 Byte 的编译错误,但 final int 到 Byte 是可以的?

Why during autoboxing final long to Byte compilation error happens, but final int to Byte is ok?

intshort 类型的常量自动装箱到 Byte 时没有错误,但是 long 类型的常量确实有错误。为什么?

final int i = 3;
Byte b = i; // no error

final short s = 3;
Byte b = s; // no error


final long l = 3;
Byte b = l; // error

来自 JLS Sec 5.2, "Assignment contexts"(强调我的):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

  • 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.
    • ...

规范根本不允许 longs。

请注意,这里的第二个要点表示无论装箱如何都会发生这种情况:将常量 long 表达式分配给 byte 变量同样会失败:

// Both compiler errors.
byte primitive = 0L;
Byte wrapped = 0L;