Get Enum instance

This question already has an answer here:

  • Lookup Java enum by string value 23 answers

  • Try this out. I have created a method which searches type using id:

    public static Type getType(int id) {
    
        for (Type type : Type.values()) {
            if (id == type.getId()) {
                return type;
            }
        }
        return null;
    }
    

    您可以构建一个映射来执行此查找。

    static final Map<Integer, Type> id2type = new HashMap<>();
    static {
        for (Type t : values())
            id2type.put(t.id, t);
    }
    public static Type forId(int id) {
        return id2type.get(id);
    }
    

    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;
    }
    
    链接地址: http://www.djcxy.com/p/38092.html

    上一篇: 从用户输入设置枚举

    下一篇: 获取Enum实例