根据我对 Java 的了解,如果 source 位于字节范围内的任何常量中,则在缩小类型转换时允许以下内容:
byte b=10; // allowed because 10 is in range of byte and 10 is a constant
但是当我输入这个时:
byte b=10l; // this is not allowed although 10 is in range of byte and is a constant
为什么会这样?
您能否说出这些缩小转换在 Java 中发生的确切规则。
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.2 :
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.
您有一个 long 类型的常量表达式,在这种情况下不能应用缩小原始转换。
所以你可以这样做:
字节 b = 10
byte b = (int) 10
char b = (short) 10
byte b = (char) 10L
短 b = (int) 10L
但是你不能这样做:
字节 b = 10L
byte b = (long) 10