Monday 20 February 2017

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 stringMap = new HashMap();

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

}

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

Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...