How can I lookup a Java enum from its String value

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I would like to lookup an enum from its string value (or possibly any other value). I ve tried the following code but it doesn t allow static in initialisers. Is there a simple way?

public enum Verbosity {

    BRIEF, NORMAL, FULL;

    private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();

    private Verbosity() {
        stringMap.put(this.toString(), this);
    }

    public static Verbosity getVerbosity(String key) {
        return stringMap.get(key);
    }
};

Answers

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

I know it s iterating over all the values, but with only 3 enum values it s hardly worth any other effort, in fact unless you have a lot of values I wouldn t bother with a Map it ll be fast enough.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1080904/how-can-i-lookup-a-java-enum-from-its-string-value

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils