Convert integer value to matching Java Enum

前端 未结 11 1236
慢半拍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.

    0 讨论(0)
  • 2020-12-02 09:01

    You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

    private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
    static {
        for (PcapLinkType type : PcapLinkType.values()) {
            intToTypeMap.put(type.value, type);
        }
    }
    
    public static PcapLinkType fromInt(int i) {
        PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
        if (type == null) 
            return PcapLinkType.DLT_UNKNOWN;
        return type;
    }
    
    0 讨论(0)
  • 2020-12-02 09:03

    There's a static method values() which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

    enum MyEnum {
        FIRST, SECOND, THIRD;
        private static MyEnum[] allValues = values();
        public static MyEnum fromOrdinal(int n) {return allValues[n];}
    }
    

    In principle, you can use just values()[i], but there are rumors that values() will create a copy of the array each time it is invoked.

    0 讨论(0)
  • 2020-12-02 09:04

    if you have enum like this

    public enum PcapLinkType {
      DLT_NULL(0)
      DLT_EN10MB(1)
      DLT_EN3MB(2),
      DLT_AX25(3),
      DLT_UNKNOWN(-1);
    
        private final int value;   
    
        PcapLinkType(int value) {
            this.value= value;
        }
    }
    

    then you can use it like

    PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
    
    0 讨论(0)
  • 2020-12-02 09:07

    As @MeBigFatGuy says, except you can make your static {...} block use a loop over the values() collection:

    static {
        for (PcapLinkType type : PcapLinkType.values()) {
            intToTypeMap.put(type.getValue(), type);
        }
    }
    
    0 讨论(0)
提交回复
热议问题