简体   繁体   English

Java枚举和Objective-C枚举

[英]Java enums and Objective-C enums

I have the following enum in Objective-C: 我在Objective-C中有以下枚举:

typedef enum {
    APIErrorOne = 1,
    APIErrorTwo,
    APIErrorThree,
    APIErrorFour
} APIErrorCode;

I use the indexes to reference an enum from an xml, for example, xml may have error = 2 , which maps to APIErrorTwo 我使用索引从xml引用枚举,例如, xml可能有error = 2 ,它映射到APIErrorTwo

My flow is I get an integer from the xml, and run a switch statement as follows: 我的流程是从xml获取一个整数,并运行switch语句,如下所示:

int errorCode = 3

switch(errorCode){
    case APIErrorOne:
        //
        break;
    [...]
}

Seems Java dislikes this kind of enum in a switch statement: 似乎Java在switch语句中不喜欢这种枚举:

在此输入图像描述

In Java it seems you can't assign indexes to enum members. 在Java中,似乎无法为enum成员分配索引。 How can I get a Java equivalent of the above ? 我怎样才能获得与上述相同的Java?

Java enums have a built-in ordinal , which is 0 for the first enum member, 1 for the second, etc. Java枚举有一个内置序号 ,第一个枚举成员为0,第二个为1,等等。

But enums are classes in Java so you may also assign them a field: 但枚举是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;
    }
} 

One question per post is the general rule here. 每篇文章的一个问题是这里的一般规则。

But evolving the JB Nizer answer. 但是不断发展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);
            }
        }

    }
}

Then in your code you can write 然后在你的代码中你可以写

int errorCode = 3

switch(APIErrorCode.getAPIErrorCodeByCode(errorCode){
    case APIErrorOne:
        //
        break;
    [...]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM