How to retrieve Enum name using the id?

前端 未结 11 1669
一整个雨季
一整个雨季 2020-12-05 13:11

I have the enum as:

public enum EnumStatus {

    PASSED(40L, \"Has Passed\"),
    AVERAGE(60L, \"Has Average Marks\"),
    GOOD(80L, \"Has Good         


        
11条回答
  •  粉色の甜心
    2020-12-05 13:49

    Sometimes the enum's ordinal has a clear relationship with this kind of ids, enabling a neat way to get O(1) in these methods. In your code, it is clear that

    EnumStatus.X = 40 + 20 * ordinal,

    so you can leverage the static array that is generated under the hoods.

    public static EnumStatus fromId(Long id) {
        int index = (id - 40L) / 20L;
        return values()[index];
    }
    

提交回复
热议问题