2012-07-11 153 views
4

我在目标C以下枚举:爪哇枚举和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语句:

enter image description here

在Java中,似乎你不能分配索引enum成员。我怎样才能获得与上述相同的Java?

回答

3

每个帖子有一个问题是这里的一般规则。

但是正在演变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; 
    [...] 
} 
+0

谢谢!你的枚举与以前的答案无关!谢谢你这个作品。 – Daniel 2012-07-11 18:35:54

+0

不得不说这是疯狂的这是多少的矫枉过正这是在Java中的枚举,我几乎会有更好的几个静态变量... – Daniel 2012-07-11 18:38:01

+0

@Daniel,我很高兴你喜欢这个解决方案。但我会用JB Nizet解决方案。在switch中,你调用'case APIErrorOne.getCode():'。编译器确保你只切换一种类型,所以不可能做'int e = 1 switch {case 1:break; case APIErrorCode:braek; }'。 – 2012-07-11 18:42:28

6

的Java枚举有一个内置的ordinal,这对于第一个枚举成员,1位第二等是0

但枚举在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; 
    } 
} 
+0

我可以设置的第一个错误序号1,并留下其他未分配的?像Objective-C一样,索引是否会级联? – Daniel 2012-07-11 18:01:19

+1

@丹尼尔,不,你不能。如果你指定一个构造函数,所有枚举项必须声明它。 – 2012-07-11 18:02:36

+1

不,你不能。总是从0开始。但是您可以添加一个返回ordinal()+ 1的方法。 – 2012-07-11 18:03:19