注意:这不是 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;
}
}
关于java - 在 Java 中使用 switch 比较字符串与枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130592/