这是一个bug。以下是《Java语言规范第3版》中
switch
语句的指定行为:
SwitchStatement:
switch ( Expression ) SwitchBlock
When the switch
statement is executed, first the Expression
is evaluated. If the Expression
evaluates to null
, a NullPointerException
is thrown and the entire switch
statement completes abruptly for that reason.
显然,Eclipse上的错误与default
case或enum
没有任何关系。
public class SwitchingOnAnull {
public static void main(String[] args) {
java.math.RoundingMode x = null;
switch(x) {};
switch((Integer) null) {};
switch((Character) null) {
default: System.out.println("I've got sunshine!");
}
}
}
上面的代码在Eclipse中编译和运行“良好”。每个单独的
switch
在使用
javac
编译时都会抛出
NullPointerException
,这正是规范所要求的。
原因
以下是在Eclipse下编译的
javap -c SwitchingOnAnull
:
Compiled from "SwitchingOnAnull.java"
public class SwitchingOnAnull extends java.lang.Object{
public SwitchingOnAnull();
Code:
0: aload_0
1: invokespecial #8;
4: return
public static void main(java.lang.String[]);
Code:
0: aconst_null
1: astore_1
2: getstatic #16;
5: ldc #22;
7: invokevirtual #24;
10: return
}
看起来Eclipse编译器完全摆脱了switch
结构。不幸的是,这种优化破坏了语言规范。
官方声明
该错误已被提交并分配进行修复。
Olivier Thomann 2010-05-28 08:37:21 EDT
We are too aggressive on the optimization.
For:
switch((Integer) null) {};
we optimize out the whole switch
statement when we should at least evaluate the
expression.
I'll take a look.
Candidate for 3.6.1.
参见