首页 > 解决方案 > 为什么`switch(null)`是一个编译错误但是`switch(str)`在str是`static final String str = null;`的情况下没问题?

问题描述

虽然switch(null)是编译错误,但switch(str)很好(strbeing 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)。

标签: javanullswitch-statementconstantscompile-time-constant

解决方案


从错误消息中:

不兼容的类型。找到'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 根本不知道您的意思是哪种类型。


推荐阅读