Check valid enum values before using enum

There is an apache commons lang EnumUtils.isValidEnum(). Unfortunately, Under the hood, this is using try/catch logic and returning boolean, but at least your code looks clean:

if(EnumUtils.isValidEnum(Fruit.class, fruitname)) { ....

You will need to use the latest commons-lang3 library as commons-lang 2.x does not have this function.


I really don't know a built-in solution. So you may have to write it yourself as a static method.

public enum Fruit {
   ...
   static public boolean isMember(String aName) {
       Fruit[] aFruits = Fruit.values();
       for (Fruit aFruit : aFruits)
           if (aFruit.fruitname.equals(aName))
               return true;
       return false;
   }
   ...
}

Tags:

Java

Enums