Convert integer value to matching Java Enum

前端 未结 11 1244
慢半拍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:48

    You can do something like this to automatically register them all into a collection with which to then easily convert the integers to the corresponding enum. (BTW, adding them to the map in the enum constructor is not allowed. It's nice to learn new things even after many years of using Java. :)

    public enum PcapLinkType {
        DLT_NULL(0),
        DLT_EN10MB(1),
        DLT_EN3MB(2),
        DLT_AX25(3),
        /*snip, 200 more enums, not always consecutive.*/
        DLT_UNKNOWN(-1);
    
        private static final Map typesByValue = new HashMap();
    
        static {
            for (PcapLinkType type : PcapLinkType.values()) {
                typesByValue.put(type.value, type);
            }
        }
    
        private final int value;
    
        private PcapLinkType(int value) {
            this.value = value;
        }
    
        public static PcapLinkType forValue(int value) {
            return typesByValue.get(value);
        }
    }
    

提交回复
热议问题