How to retrieve Enum name using the id?

前端 未结 11 1690
一整个雨季
一整个雨季 2020-12-05 13:11

I have the enum as:

public enum EnumStatus {

    PASSED(40L, \"Has Passed\"),
    AVERAGE(60L, \"Has Average Marks\"),
    GOOD(80L, \"Has Good         


        
11条回答
  •  情书的邮戳
    2020-12-05 13:48

    Define contract

    /**
     * Contract that will allow Types with id to have generic implementation.
     */
    public interface IdentifierType {
      T getId();
    }
    

    Apply contract

    public enum EntityType implements IdentifierType {
      ENTITY1(1, "ONE), ENTITY2(2, "TWO");
    
      private Integer id;
      private String name;
    
      private EntityType(int id, String name) {
        this.id = id;
        this.name = name;
      }
    
      public static EntityType valueOf(Integer id) {
        return EnumHelper.INSTANCE.valueOf(id, EntityType.values());
      }
    
      @Override
      public Integer getId() {
        return id;
      }
    }
    

    Helper/Util

    public enum EnumHelper {
      INSTANCE;
    
      /**
       * This will return {@link Enum} constant out of provided {@link Enum} values with the specified id.
       * @param id the id of the constant to return.
       * @param values the {@link Enum} constants of specified type.
       * @return the {@link Enum} constant.
       */
      public , S> T valueOf(S id, T[] values) {
        if (!values[0].getClass().isEnum()) {
            throw new IllegalArgumentException("Values provided to scan is not an Enum");
        }
    
        T type = null;
    
        for (int i = 0; i < values.length && type == null; i++) {
            if (values[i].getId().equals(id)) {
                type = values[i];
            }
        }
    
        return type;
      }
    }
    

提交回复
热议问题