可能重复:
在交换机/案例中使用枚举
给定枚举
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
(
请问如何纠正?
一种非映射方法是像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:
...
您需要创建一个出口代码到ExitCode
枚举值的映射。然后你可以做
switch(ExitCode.lookup(exitCode)) {
case PROGRAM_FINSHED_SUCCESSFULLY:
我们在工作中也有类似的模式。
更改您的枚举类以添加反向查找映射:
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