为什么`switch(null)`是编译错误,但是`switch(str)`可以,因为str是`static final String str = null;`?

Cod*_*ete 3 java null constants compile-time-constant switch-statement

虽然switch(null)是一个编译错误,但是switch(str)很好(strstatic final String str = null;)。

难道不是static final String str = null; 在编译时就将其替换为switch(str)的编译时常量switch(null)吗?

switch (null) {  // compile Error immediately!

}
Run Code Online (Sandbox Code Playgroud)

但:

public class Test {

    // compile-time constant?
    static final String s4 = null; 

    public static void main(String[] args) {

        switch (s4) {  // compiles fine! NPE at runtime

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

PS我想这static final String str = null; 不是一个编译时常量,因为只有static final String str = 'string literal'一个编译时常量,这解释了上面的示例(s4)。

Lin*_*ica 7

从错误消息:

不兼容的类型。找到“ null”,必需:“ char,byte,short,int,Character,Byte,Integer,String或enum”

你可以看到,null被推断为无,它甚至不是一个Object,它简单的“零式”,而不是String(或任何其他有效的可切换式)。

因此,要进行编译,您需要将其强制转换为String(或其他有效类型之一)。

switch((String) null) {
Run Code Online (Sandbox Code Playgroud)

RuntimeException当您尝试执行它时,它将抛出一个。

switch实际上,此行为不仅适用于您执行此操作时的行为:

null.isEmpty()
Run Code Online (Sandbox Code Playgroud)

java如何知道您要调用的内容String#isEmpty()?你也可以这样说Collection#isEmpty()。或任何其他isEmpty()方法。这同样适用于在switch-example,JAVA根本不知道你的意思是哪种类型。