I have the following enum
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 had originally used the Enum.valueOf(Animal.class, "DOG");
to find a particular Animal. However, I was unaware that if a match is not found, an IllegalArgumentException
is thrown. I thought that maybe a null was returned. So this gives me a problem. I don't want to catch this IllegalArgumentException
if a match is not found. I want to be able to search all enums of type Mammal
and I don't want to have to implement this static 'findMammal
' for each enum of type Mammal
. So my question is, what would be the most auspicious design decision to implement this behaviour? I will have calling code like this:
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 Mammal - 'Animal', 'Human', which are enums. I don't want to have to implement 'findMammal' for each Mammal enum. I suppose the best bet is just create a utility class which takes a Mammal argument and searches that? Maybe there's a neater solution.
I don't get the question but I also needed a valueOf
that returns null
instead of throwing an exception, so I created this utility method:
public static <T extends Enum<T>> T valueOf(T[] values, String name)
{
for (T value : values) {
if (value.name().equals(name)) {
return value;
}
}
return null;
}
You could call it like this:
Animal a = valueOf(Animal.values(), "CAT");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With