且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将枚举的字符串结果重写为enum?

更新时间:2022-11-11 13:53:16

***最简单的方法就是这样:

  public enum AgeRange {
A18TO23(18-23),
A24TO29(24-29),
A30TO35(30-35);

private String value;

AgeRange(String value){
this.value = value;
}

public String toString(){
返回值;
}

public static AgeRange getByValue(String value){
for(final AgeRange element:EnumSet.allOf(AgeRange.class)){
if(element。 toString()。equals(value)){
return element;
}
}
返回null;
}
}

然后你只需要调用 getByValue()方法与 String 输入。


Given the following java enum:

public enum AgeRange {

   A18TO23 {
        public String toString() {        
            return "18 - 23";
        }
    },
   A24TO29 {
        public String toString() {        
            return "24 - 29";
        }
    },
   A30TO35 {
        public String toString() {        
            return "30 - 35";
        }
    },

}

Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ?

Thanks!

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.