Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving an enum using 'valueOf' throws RuntimeException - What to use instead?

Tags:

java

enums

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.

like image 460
Joeblackdev Avatar asked Feb 21 '12 19:02

Joeblackdev


1 Answers

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");
like image 181
Ferran Maylinch Avatar answered Oct 19 '22 09:10

Ferran Maylinch