注意:这不是Java switch statement: Constant expression required, but it IS constant的副本,因为此处已经应用了该链接的解决方案。
在带有打字稿的Cordova应用中,我使用此枚举发送我的操作=
打字稿
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
}
我想比较打字稿PluginActions
与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;
}
但我在这里遇到错误: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;
}
但是关于case PickerAction.Pick
错误:枚举开关大小写标签必须是枚举常量的不合格名称
答案 0 :(得分:2)
我建议您为Java枚举使用String值:
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;
}
}
答案 1 :(得分:2)
错误:枚举开关大小写标签必须是枚举常量的不合格名称, 您不应使用案例PickerActions.PICK,而只能使用以下案例,
public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;
switch(ch) {
case Choice1:
System.out.println("Choice1 selected");
break;
case Choice2:
System.out.println("Choice2 selected");
break;
case Choice3:
System.out.println("Choice3 selected");
break;
}
}
}