Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enums and Objective-C enums

I have the following enum in 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

My flow is I get an integer from the xml, and run a switch statement as follows:

int errorCode = 3

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

Seems Java dislikes this kind of enum in a switch statement:

enter image description here

In Java it seems you can't assign indexes to enum members. How can I get a Java equivalent of the above ?

like image 381
Daniel Avatar asked Jan 17 '23 03:01

Daniel


2 Answers

Java enums have a built-in ordinal, which is 0 for the first enum member, 1 for the second, etc.

But enums are classes in Java so you may also assign them a field:

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;
    }
} 
like image 80
JB Nizet Avatar answered Jan 22 '23 16:01

JB Nizet


One question per post is the general rule here.

But evolving the JB Nizer answer.

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;
    [...]
}
like image 31
Damian Leszczyński - Vash Avatar answered Jan 22 '23 16:01

Damian Leszczyński - Vash