Java 带字符串的 switch 语句中的常量表达式需要错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31915793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:45:58  来源:igfitidea点击:

Constant expression required error in switch statement with strings

javaandroidstringenumsswitch-statement

提问by Isuru

I get a JSON response which roughly looks like this.

我得到一个大致如下所示的 JSON 响应。

{
  "status": "success",
  "data": [
    {
      ....
    }
  ]
}

The statusfield can have two values: successor fail.

status字段可以有两个值:successfail

So in my code, I have the following enum.

所以在我的代码中,我有以下枚举。

private enum Status {
    SUCCESS("success", 0),
    FAIL("fail", 1);

    private String stringValue;
    private int intValue;
    private Status(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

What I want to do is in a switch statement, I need to check for the status value and execute code in each condition.

我想要做的是在 switch 语句中,我需要检查状态值并在每个条件下执行代码。

String status = jsonObj.getString("status");

switch (status) {
    case Status.SUCCESS.toString():
        Log.d(LOG_TAG, "Response is successful!");
    case Status.FAIL.toString():
        Log.d(LOG_TAG, "Response failed :(");
    default:
        return;
}

But I get the Constant expression requirederror at each case.

但是我在每种情况下都会得到Constant expression required错误。

I checked the value returned by Status.SUCCESS.toString()and Status.FAIL.toString()which indeed return strings.

我检查了返回的值,Status.SUCCESS.toString()并且Status.FAIL.toString()确实返回了字符串。

Any idea why this error still occur?

知道为什么这个错误仍然发生吗?

采纳答案by Bathsheba

casestatements have to be compile-time evaluable.

case语句必须是编译时可评估的。

Something like Status.SUCCESS.toString()doesn't satisfy that. A string literal, on the other hand, does.

类似的东西Status.SUCCESS.toString()不能满足这一点。另一方面,字符串文字可以。

The obvious fix is to use an an ifblock.

显而易见的解决方法是使用一个if块。