[英]Java enums and Objective-C enums
我在Objective-C中有以下枚举:
typedef enum {
APIErrorOne = 1,
APIErrorTwo,
APIErrorThree,
APIErrorFour
} APIErrorCode;
我使用索引从xml引用枚举,例如, xml
可能有error = 2
,它映射到APIErrorTwo
我的流程是从xml获取一个整数,并运行switch语句,如下所示:
int errorCode = 3
switch(errorCode){
case APIErrorOne:
//
break;
[...]
}
似乎Java在switch语句中不喜欢这种枚举:
在Java中,似乎无法为enum
成员分配索引。 我怎样才能获得与上述相同的Java?
Java枚举有一个内置序号 ,第一个枚举成员为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;
}
}
每篇文章的一个问题是这里的一般规则。
但是不断发展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;
[...]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.