How can I lookup a Java enum from its String value?

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);
    }
};

12 Answers
12

Leave a Comment