使用 Java 中的 switch 比较字符串和枚举值

dis*_*nte 5 java enums

注意:这不是Java switch 语句的重复:需要常量表达式,但它是常量,因为该链接的解决方案已在此处应用。


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

打字稿

enum PluginActions {
   PICK = "PICK",
   PICK_MULTIPLE = "PICK_MULTIPLE"
}
Run Code Online (Sandbox Code Playgroud)

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

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

  }

Run Code Online (Sandbox Code Playgroud)

那里我还有一个枚举。

爪哇

enum PickerActions {
  PICK, PICK_MULTIPLE
}
Run Code Online (Sandbox Code Playgroud)

我想比较 typescriptPluginActions和 java PickerActions

使用if我可以使用:

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

但我想用一个开关来做到这一点,这样我就可以轻松添加更多操作

  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;      
  }

Run Code Online (Sandbox Code Playgroud)

但我在那里得到一个错误:error: constant string expression required

有没有办法在 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;      
    }
Run Code Online (Sandbox Code Playgroud)

但我在那里收到另一个错误case PickerAction.Pick

错误:枚举 switch case 标签必须是枚举常量的非限定名称

Pau*_*aul 6

您可以在您的开关案例中使用java.lang.Stringjava.lang.Enum并对其进行测试。

但是,就像@SpencerSprowls在评论中所说,java.lang.IllegalArgumentException如果您使用的值与您的java.lang.Enum.

因此,在交换机中添加默认情况是没有用的。为了避免抛出不需要的异常,您可以将java.lang.Enum值转换为 anjava.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;      
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例