"how to convert string result of enum with overridden tostring() back to enum?" Code Answer

3

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.

By ?s??o? on July 2 2022

Answers related to “how to convert string result of enum with overridden tostring() back to enum?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.