为什么编译失败并出现“case 表达式必须是常量表达式”错误?不是 null
一个常量(在编译时已知)?
显式转换 null
值转换为字符串,如case ((String)null)
也没有帮助(我得到同样的错误)。
public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case null:
typeOfDay = "NULL";
break;
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
最佳答案
是的,case 表达式必须是常量表达式,但 JLS, Section 14.11 明确禁止 null
,它描述了 switch
语句:
Given a switch statement, all of the following must be true or a compile-time error occurs:
Every case constant associated with the switch statement must be assignment compatible with the type of the switch statement's Expression (§5.2).
If the type of the switch statement's Expression is an enum type, then every case constant associated with the switch statement must be an enum constant of that type.
No two of the case constants associated with the switch statement have the same value.
No case constant associated with the switch statement is null.
At most one default label is associated with the switch statement.
(斜体强调我的)
作为解决方法,您可以在 switch
语句之外测试 null
。
关于Java 7 - null 作为 case 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30313765/