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

后端 未结 6 836
醉话见心
醉话见心 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:13

    You could try something like the following?

    static AgeRange fromString(String range) {
        for (AgeRange ageRange : values()) {
            if (range.equals(ageRange.toString())) {
                return ageRange;
            }
        }
        return null;   
    }
    

    Or, as others suggested, using a caching approach:

    private static Map map;
    
    private static synchronized void registerAgeRange(AgeRange ageRange) {
        if (map == null) {
            map = new HashMap();
        }
        map.put(ageRange.toString(), ageRange);
    }
    
    AgeRange() {
        registerAgeRange(this);
    }
    
    static AgeRange fromString(String range) {
        return map.get(range);
    }
    

提交回复
热议问题