Maria Maria - 7 months ago 12
Java Question

Get Enum instance

I have an

Enum
:

public enum Type {

ADMIN(1),
HIRER(2),
EMPLOYEE(3);

private final int id;

Type(int id){
this.id = id;
}

public int getId() {
return id;
}
}


How can I get a
Type
enum passing an
id
property?

Answer

Create a method inside the Type class returning the Enum instances:

Type get(int n) {
    switch (n) {
    case 1:
        return Type.ADMIN;
    case 2:
        return Type.EMPLOYEE;
    case 3:
        return Type.HIRER;
    default:
        return null;
    }

}

TIP: you need to add default in switch-case or add a return null at the end of the method to avoid compiler errors.


UPDATE (thanks to @AndyTurner):

It would be better to loop and refer to the id field, so you're not duplicating the IDs.

Type fromId(int id) {
    for (Type t : values()) {
        if (id == t.id) {
            return t;
        }
    }
    return null;
}
Comments