Convert integer value to matching Java Enum

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

    I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional, I thought I'd offer up a solution using it (and Stream and Collectors):

    public enum PcapLinkType {
      DLT_NULL(0),
      DLT_EN3MB(2),
      DLT_AX25(3),
      /*snip, 200 more enums, not always consecutive.*/
      // DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED
    
      private final int value;
      private PcapLinkType(int value) { this.value = value; }
    
      private static final Map map;
      static {
        map = Arrays.stream(values())
            .collect(Collectors.toMap(e -> e.value, e -> e));
      }
    
      public static Optional fromInt(int value) {
        return Optional.ofNullable(map.get(value));
      }
    }
    

    Optional is like null: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null or a default value such as DLT_UNKNOWN because you could forget to check for the null or DLT_UNKNOWN cases. They are both valid PcapLinkType values! In contrast, you cannot assign an Optional value to a variable of type PcapLinkType. Optional makes you check for a valid value first.

    Of course, if you want to retain DLT_UNKNOWN for backward compatibility or whatever other reason, you can still use Optional even in that case, using orElse() to specify it as the default value:

    public enum PcapLinkType {
      DLT_NULL(0),
      DLT_EN3MB(2),
      DLT_AX25(3),
      /*snip, 200 more enums, not always consecutive.*/
      DLT_UNKNOWN(-1);
    
      private final int value;
      private PcapLinkType(int value) { this.value = value; }
    
      private static final Map map;
      static {
        map = Arrays.stream(values())
            .collect(Collectors.toMap(e -> e.value, e -> e));
      }
    
      public static PcapLinkType fromInt(int value) {
        return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
      }
    }
    

提交回复
热议问题