Java – use ‘valueof’ to retrieve an enumerated throws runtimeException – what is used?
I have the following enumeration
enum Animal implements Mammal {
CAT,DOG;
public static Mammal findMammal(final String type) {
for (Animal a : Animal.values()) {
if (a.name().equals(type)) {
return a;
}
}
}
}
I initially used enum valueOf(Animal.class,“DOG”); Find a specific animal However, I didn't know that if no match was found, an illegalargumentexception would be thrown I thought maybe a null was returned So this gives me a question If no match is found, I don't want to catch this illegalargumentexception I want to be able to search all enumerations of type mammal. I don't want to implement this static "findmammal" for every enumeration of type mammal So my question is, what is the most auspicious design decision to perform this behavior? I will have this calling code:
public class Foo {
public Mammal bar(final String arg) {
Mammal m = null;
if (arg.equals("SomeValue")) {
m = Animal.findMammal("CAT");
} else if (arg.equals("AnotherValue") {
m = Human.findMammal("BILL");
}
// ... etc
}
}
As you can see, I have different types of mammals - "animals", "people", they are enumerations I don't want to implement "findmammal" for every mammal enumeration I think the best bet is just to create a utility class that requires a mammalian parameter and search? Perhaps there is a more complete solution
Solution
How to create HashMap < string, MMAL >? 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:
>If the name does not exist, return null > this will not find name conflicts > you may want to use some immutable maps (for example, through guava) > you may want to write a utility method to create an immutable name to the map for ordinary enumeration, and then just merge the map:)
