java - 在 Java 中使用 switch 比较字符串与枚举值

标签 java enums

注意:这不是 Java switch statement: Constant expression required, but it IS constant 的副本因为该链接的解决方案已在此处应用。


在带有 typescript 的 Cordova 应用程序中,我使用此枚举来发送我的操作 =

typescript

enum PluginActions {
   PICK = "PICK",
   PICK_MULTIPLE = "PICK_MULTIPLE"
}

我将其发送到 cordova,在 Java 中,我将其作为方法中的 action 字符串变量获取。

@Override
  public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {

  }

我还有一个枚举。

Java

enum PickerActions {
  PICK, PICK_MULTIPLE
}

我想比较 typescript PluginActions 与 java PickerActions

使用 if 我可以使用:

if (action.equals(PickerActions.PICK.name())) { }

但我想用一个开关来做,这样我就可以轻松地添加更多 Action

  switch (action) {
    case PickerActions.PICK.name():
      JSONObject filters = inputs.optJSONObject(0);
      this.chooseFile(filters, callbackContext);
      return true;
    default:
    Log.w(this.LOGGER_TAG, "No function was found for " + action);
    return false;      
  }

但我在那里遇到错误:错误:需要常量字符串表达式

有没有办法在 switch 语句中使用枚举字符串名称?

编辑:

根据@Arnaud 的建议,我以这种方式转换枚举的值:

final PickerActions pickerAction = FilePickerActions.valueOf(action);

    switch (pickerAction ) {
      case PickerActions.PICK:
        JSONObject filters = inputs.optJSONObject(0);
        this.chooseFile(filters, callbackContext);
        return true;
      default:
      Log.w(this.LOGGER_TAG, "No function was found for " + action);
      return false;      
    }

但是我在 case PickerAction.Pick 方面遇到了另一个错误

error: an enum switch case label must be the unqualified name of an enumeration constant

最佳答案

您可以使用 java.lang.String java.lang.Enum 中的值并在您的 switch 案例中针对它进行测试。

但是,像@SpencerSprowls在评论中说,它会抛出一个 java.lang.IllegalArgumentException如果您使用的值与您的 java.lang.Enum 的任何值都不匹配.

因此,在您的 switch 中添加 default case 是没有用的。为避免抛出不需要的异常,您可以转换 java.lang.Enum java.util.EnumMap 的值并检查它是否与切换前的现有值匹配 EnumMap#containsValue

private enum PickerActions {
    PICK("PICK"),
    PICK_MULTIPLE("PICK_MULTIPLE");
    private final String value;
    PickerActions(final String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return value;
    }
}
    
private static boolean test(String test) {
     switch (PickerActions.valueOf(test)) {
        case PICK:
            //
            return true;
        case PICK_MULTIPLE:
            //
            return false;
        // default:
            // This will never happen
            // return false;      
    }
}

Here is a working example

关于java - 在 Java 中使用 switch 比较字符串与枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130592/

相关文章:

java - 检测当前时间是否在两个设置时间之间

java - Bean创建拦截器

c - 此 C 代码如何返回枚举?

c# - 枚举类型参数不起作用

c++11 - 枚举 : int and enum : const int 之间有什么区别吗

java - 无法在项目 jraft 上执行目标 org.sonarsource.scanner.maven :sonar-maven-plugin:3. 3.0.603:sonar (default-cli):没有治理许可

java - 客户端和服务器之间的安全连接

java - 删除java中URL中斜杠之间的所有字符

c++ - 从 bool 值构造具有底层 "bool"类型的枚举?

c# - 枚举类型的值