Retrieving an enum using 'valueOf' throws RuntimeException - What to use instead?
You can use the getEnum Method vom the apache EnumUtils library. It returns the enum or null
if not found.
EnumUtils.getEnum(Animal.class, "CAT");
How about creating a HashMap<String, Mammal>
? You only need to do it once...
public class Foo {
private static final Map<String, Mammal> NAME_TO_MAMMAL_MAP;
static {
NAME_TO_MAMMAL_MAP = new HashMap<String, Mammal>();
for (Human human : EnumSet.allOf(Human.class)) {
NAME_TO_MAMMAL_MAP.put(human.name(), human);
}
for (Animal animal : EnumSet.allOf(Animal.class)) {
NAME_TO_MAMMAL_MAP.put(animal.name(), animal);
}
}
public static Mammal bar(final String arg) {
return NAME_TO_MAMMAL_MAP.get(arg);
}
}
Notes:
- This will return
null
if the name doesn't exist - This won't detect a name collision
- You may want to use an immutable map of some description (e.g. via Guava)
- You may wish to write a utility method to create an immutable name-to-value map for a general enum, then just merge the maps :)