为什么java switch 语句不能处理null,因为它有一个default"子句?
Why java switch statement can't handle null, since it has a "default" clause?
例如,如果你有类似的东西
For example, if you have something like
switch(value){ case VAL1: do_something1(); break; case VAL2: do_something2(); break; default: do_something3(); }default"不应该处理任何其他值,例如 null?
shouldn't "default" deal with any other value, such as null?
推荐答案一如既往,它在 JLS 中:
以下所有条件都必须为真,否则会发生编译时错误:
- ...
- 没有开关标签是null.
...禁止使用 null 作为开关标签可以防止编写永远无法执行的代码.如果 switch 表达式是引用类型,即 String 或装箱的原始类型或枚举类型,那么如果表达式的计算结果为 null 在运行时.在 Java 编程语言的设计者的判断中,这比默默地跳过整个 switch 语句或选择执行 default 之后的语句(如果有)更好的结果> 标签(如果有的话).
... The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, that is, String or a boxed primitive type or an enum type, then a run-time error will occur if the expression evaluates to null at run time. In the judgment of the designers of the Java programming language, this is a better outcome than silently skipping the entire switch statement or choosing to execute the statements (if any) after the default label (if any).
更多推荐
为什么 java switch 语句不能处理 null,因为它有一个“默认"条款?
发布评论