java - 为什么`switch(null)`是一个编译错误但是`switch(str)`在str是`static final String str = null;`的情况下没问题?
问题描述
虽然switch(null)
是编译错误,但switch(str)
很好(str
being static final String str = null;
)。
不是static final String str = null;
一个编译时常量,它应该switch(str)
在编译时被替换,因此相当于switch(null)
?
switch (null) { // compile Error immediately!
}
但:
public class Test {
// compile-time constant?
static final String s4 = null;
public static void main(String[] args) {
switch (s4) { // compiles fine! NPE at runtime
}
}
}
PS我想static final String str = null;
不是编译时常量,因为只是static final String str = 'string literal'
编译时常量,这解释了上面的例子(s4)。
解决方案
从错误消息中:
不兼容的类型。找到'null',必需:'char、byte、short、int、Character、Byte、Integer、String 或 enum'
您可以看到它null
被推断为什么都没有,它甚至不是 a Object
,它只是“空类型”,而不是 a String
(或任何其他有效的可切换类型)。
因此,要编译它,您需要将其转换为String
(或其他有效类型之一)。
switch((String) null) {
然后RuntimeException
当您尝试执行它时会抛出一个。
此行为不仅适用于switch
它实际上与您执行此操作时相同:
null.isEmpty()
java应该如何知道你想要调用String#isEmpty()
?你也可以说Collection#isEmpty()
. 或者任何其他isEmpty()
方法。-example也是如此switch
,java 根本不知道您的意思是哪种类型。
推荐阅读
- html - 如何以正确的方式对齐我的 flexbox 项目?
- cmyk - 如何使用 Magick.Net 将 RGB 位图数据保存为 CMYK tiff
- php - 将最小第二个偶数和最大第二个偶数相加:
- mysql - MYSQL 使用案例从 curdate() 中减去天数
- excel - VBA添加一个新工作表,如果名称存在添加一个数字
- javascript - 在 FormArray 中获取唯一值 - Angular
- r - 如何为重复值创建序列列?
- video - ffmpeg 使用图像和视频制作幻灯片
- unity3d - 如何将对象投射到游戏对象?
- json - REST API 中的链接应该放在响应标头还是正文中?