Java 7 - null 作为 case 表达式

标签 java

为什么编译失败并出现“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/

相关文章:

运行appium脚本时出现java.lang.ClassNotFoundException

java - Android ViewPager fragment - 没有滑动和预加载?

java - Android Tablayout,为什么标签不移动?

java - Java 中的 CSV 到表

java - 使用流过滤集合以获取其属性在 Java 8 中出现 n 次的项目

java - groovy中的POGO是什么

java - 向客户端广播消息

java - 如何设置登录页面路径

java - 如何找到 "Could not resolve placeholder"原因

java - 如何在 servlet 中处理浏览器关闭事件