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

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

    The best and simplest way to do it is like this:

    public enum AgeRange {
        A18TO23 ("18-23"),
        A24TO29 ("24-29"),
        A30TO35("30-35");
    
        private String value;
    
        AgeRange(String value){
            this.value = value;
        }
    
        public String toString(){
            return value;
        }
    
        public static AgeRange getByValue(String value){
            for (final AgeRange element : EnumSet.allOf(AgeRange.class)) {
                if (element.toString().equals(value)) {
                    return element;
                }
            }
            return null;
        }
    }
    

    Then you just need to invoke the getByValue() method with the String input in it.

提交回复
热议问题