在使用int和short类型的常量自动装箱期间没有错误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
Run Code Online (Sandbox Code Playgroud)
And*_*ner 16
从JLS Sec 5.2,"Assignment contexts"(强调我的):
此外,如果表达式是byte,short,char或int类型的常量表达式(第15.28节):
- 如果变量的类型是byte,short或char,则可以使用缩小的基元转换,并且常量表达式的值可以在变量的类型中表示.
如果变量的类型是:则可以使用缩小的基元转换,然后进行装箱转换:
- 字节和常量表达式的值可在类型字节中表示.
- ...
long根据规范,它根本不允许使用.
请注意,此处的第二个要点是,无论装箱如何都会发生这种情况:long为byte变量分配常量表达式同样会失败:
// Both compiler errors.
byte primitive = 0L;
Byte wrapped = 0L;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
526 次 |
| 最近记录: |