How to convert string result of enum with overridden toString() back to enum?

后端 未结 6 838
醉话见心
醉话见心 2021-01-31 10:30

Given the following java enum:

public enum AgeRange {

   A18TO23 {
        public String toString() {        
            return \"18 - 23\";
        }
    },
          


        
6条回答
  •  一向
    一向 (楼主)
    2021-01-31 11:14

    According to effective java (2nd ed) item 30, it can be (it is much faster than the loop)

    public enum AgeRange {
           A18TO23("18-23"),
           A24TO29("24-29"),
           A30TO35("30-35");
    
           private final String value;
    
           AgeRange(String value){
              this.value = value;
           }
    
           @Override public String toString(){
               return value;
           }
    
           private static final Map stringToEnum =
               new HashMap();
    
           static {
               for (AgeRange r : values()) {
                   stringToEnum.put(r.toString(), r);
               }
           }
    
           public static AgeRange getByValue(String value){
               return stringToEnum.get(value);
           }
    }
    

提交回复
热议问题