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:
In Java it seems you can't assign indexes to enum
members. How can I get a Java equivalent of the above ?
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;
}
}
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;
[...]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With