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

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

Given the following java enum:

public enum AgeRange {

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


        
6条回答
  •  情话喂你
    2021-01-31 10:56

    The class overrides "toString()" - so, to get the reverse operation, you need to override valueOf() to translate the output of toString() back to the Enum values.

    public enum AgeRange {
    
       A18TO23 {
            public String toString() {        
                    return "18 - 23";
            }
            public AgeRange valueOf (Class enumClass, String name) {
                    return A18T023
            }
        },
    
        .
        .
        .
    }
    

    Buyer beware - uncompiled and untested...

    The mechanism for toString() and valueOf() is a documented part of the API

提交回复
热议问题