给定枚举
public enum ExitCodes {
DESPITE_MULTIPLE_ATTEMPTS_CONNECTION_TO_SERVER_FAILED(-1),
PROGRAM_FINISHED_SUCCESSFULLY(0),
// ... more stuff
private final int id;
ExitCodes(final int id) {
this.id = id;
}
public int getValue() {
return id;
}
}
作为另一个班级的一部分,我想
switch (exitCode) {
case ExitCodes.PROGRAM_FINISHED_SUCCESSFULLY.getValue():
// do stuff
Constant expression required
这是为什么?据我了解,ExitCodes
中分配给id的数值是常量(final
)
请问如何纠正?
答案 0 :(得分:2)
非映射方法是在ExitCodes
中“遍历”枚举条目:
public static ExitCodes getByID(int id) {
for (final ExitCodes element : EnumSet.allOf(ExitCodes.class)) {
if (element.id == id) {
return element;
}
}
throw new IllegalArgumentException("Can't find " + id);
}
然后查找你可以做:
switch (ExitCodes.getByID(exitCode)) {
case PROGRAM_FINSHED_SUCCESSFULLY:
...
答案 1 :(得分:1)
您需要创建一个退出代码映射到ExitCode
枚举值。然后就可以了
switch(ExitCode.lookup(exitCode)) {
case PROGRAM_FINSHED_SUCCESSFULLY:
答案 2 :(得分:1)
我的工作也有类似的模式。
更改您的枚举类以添加反向查找地图:
public enum ExitCodes {
// All the same until here
private static HashMap<Integer, ExitCodes> valueToExitCodeMap = null;
public static ExitCodes getEnumByValue(int value)
{
if(valueToExitCodeMap == null)
{
valueToExitCodeMap = new HashMap<Integer, ExitCodes>();
for(ExitCodes code : values())
{
valueToExitCodeMap.put(new Integer(code.id), code);
}
}
return valueToExitCodeMap.get(new Integer(value));
}
}
然后改变这个:
switch (ExitCodes.getEnumByValue(exitCode)) {
case PROGRAM_FINISHED_SUCCESSFULLY:
// do stuff