Convert integer value to matching Java Enum

前端 未结 11 1242
慢半拍i
慢半拍i 2020-12-02 08:18

I\'ve an enum like this:

public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecu         


        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 08:57

    You will have to make a new static method where you iterate PcapLinkType.values() and compare:

    public static PcapLinkType forCode(int code) {
        for (PcapLinkType typе : PcapLinkType.values()) {
            if (type.getValue() == code) {
                return type;
            }
        }
        return null;
     }
    

    That would be fine if it is called rarely. If it is called frequently, then look at the Map optimization suggested by others.

提交回复
热议问题