Get enum by its inner field

后端 未结 5 1338
清歌不尽
清歌不尽 2020-11-27 15:48

Have enum with inner fields, kind of map.

Now I need to get enum by its inner field.

Wrote this:

package test;

/**
 * Test enum to test enum         


        
5条回答
  •  星月不相逢
    2020-11-27 16:37

    Here is the most convenient way to find enum value by its field:

    public enum TestEnum {
    
      A("EXAMPLE_1", "Qwerty", 1),
      B("EXAMPLE_2", "Asdfgh", 2),
      C("EXAMPLE_3", "Zxcvbn", 3);
    
      private final String code;
      private final String name;
      private final Integer typeID;
    
      TestEnum(String code, String name, Integer typeID) {
        this.code = code;
        this.name = name;
        this.key = typeID;
      }
    
      public String getCode() {
        return code;
      }
    
      public String getName() {
        return name;
      }
    
      public Integer getKey() {
        return key;
      }
    
      public static TestEnum findValueByTypeId(Integer key) {
        return Arrays.stream(TestEnum.values()).filter(v ->
            v.getKey().equals(key)).findFirst().orElseThrow(() ->
            new Exception(String.format("Unknown TestEnum.key: '%s'", key)));
      }
    }
    

提交回复
热议问题