Compare string with enum value using switch in Java

distante :

Note: This is not a duplicate of Java switch statement: Constant expression required, but it IS constant because the solution to that link was already applied here.


In a Cordova App with typescript I use this enum to send my actions =

typescript

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

I send that to cordova and in Java I get that as an action string variable in my method.

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

  }

There I also have an enum.

Java

enum PickerActions {
  PICK, PICK_MULTIPLE
}

I want to compare the typescript PluginActions vs the java PickerActions.

Using if I can do it using:

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

but I wan to do it with a switch so I can easily add more actions

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

But I get an error there: error: constant string expression required

Is there a way to use an enum string name in a switch statement?

Edit:

As per @Arnaud recommendation I casted the value of the enum in this way:

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

But I get another error there regarding case PickerAction.Pick

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

Paul :

I suggest your use String values for your Java enum :

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:
            // Log.w(this.LOGGER_TAG, "No function was found for " + test);
            return false;      
    }
}

Here is a working example

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310522&siteId=1