簡體   English   中英

Java枚舉和Objective-C枚舉

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM