我在Objective-C中有以下枚举:
typedef enum {
APIErrorOne = 1,
APIErrorTwo,
APIErrorThree,
APIErrorFour
} APIErrorCode;我使用索引来引用xml中的枚举,例如,xml可能有映射到APIErrorTwo的error = 2
我的流程是从xml获取一个整数,然后运行switch语句,如下所示:
int errorCode = 3
switch(errorCode){
case APIErrorOne:
//
break;
[...]
}Java似乎不喜欢switch语句中的这种枚举:

在Java语言中,似乎不能将索引分配给enum成员。我如何才能获得与上面的Java等价物?
发布于 2012-07-12 02:31:54
这里的一般规则是每个帖子一个问题。
但JB Nizer的答案在不断演变。
public enum APIErrorCode {
APIErrorOne(1),
APIErrorTwo(27),
APIErrorThree(42),
APIErrorFour(54);
private final int code;
private APIErrorCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static APIErrorCode getAPIErrorCodeByCode(int error) {
if(Util.errorMap.containsKey(error)) {
return Util.errorMap.get(error);
}
//Or create some default code
throw new IllegalStateException("Error code not found, code:" + error);
}
//We need a inner class because enum are initialized even before static block
private static class Util {
private static final Map<Integer,APIErrorCode> errorMap = new HashMap<Integer,APIErrorCode>();
static {
for(APIErrorCode code : APIErrorCode.values()){
errorMap.put(code.getCode(), code);
}
}
}
}然后你可以在你的代码中写下
int errorCode = 3
switch(APIErrorCode.getAPIErrorCodeByCode(errorCode){
case APIErrorOne:
//
break;
[...]
}发布于 2012-07-12 01:57:11
Java枚举有一个内置的ordinal,第一个枚举成员为0,第二个枚举成员为1,依此类推。
但是枚举是Java中的类,所以您还可以为它们分配一个字段:
enum APIErrorCode {
APIErrorOne(1),
APIErrorTwo(27),
APIErrorThree(42),
APIErrorFour(54);
private int code;
private APIErrorCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
} https://stackoverflow.com/questions/11438536
复制相似问题