Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if enum exists in Java

Is there anyway to check if an enum exists by comparing it to a given string? I can't seem to find any such function. I could just try to use the valueOf method and catch an exception but I'v been taught that catching runtime exceptions is not good practice. Anybody have any ideas?

like image 334
Danny Avatar asked Jul 22 '09 20:07

Danny


People also ask

How do you validate enums?

Validating That a String Matches a Value of an Enum For this, we can create an annotation that checks if the String is valid for a specific enum. This annotation can be added to a String field and we can pass any enum class.

Why do enums exist?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.


1 Answers

If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.

Sample code:

import java.util.*;  enum SampleEnum {     Foo,     Bar;      private static final Map<String, SampleEnum> nameToValueMap =         new HashMap<String, SampleEnum>();          static {         for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {             nameToValueMap.put(value.name(), value);         }     }          public static SampleEnum forName(String name) {         return nameToValueMap.get(name);     } }  public class Test {     public static void main(String [] args)         throws Exception { // Just for simplicity!         System.out.println(SampleEnum.forName("Foo"));         System.out.println(SampleEnum.forName("Bar"));         System.out.println(SampleEnum.forName("Baz"));     } } 

Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

import java.util.*;  enum SampleEnum {     Foo,     Bar;      // We know we'll never mutate this, so we can keep     // a local copy.     private static final SampleEnum[] copyOfValues = values();          public static SampleEnum forName(String name) {         for (SampleEnum value : copyOfValues) {             if (value.name().equals(name)) {                 return value;             }         }         return null;     } }  public class Test {     public static void main(String [] args)         throws Exception { // Just for simplicity!         System.out.println(SampleEnum.forName("Foo"));         System.out.println(SampleEnum.forName("Bar"));         System.out.println(SampleEnum.forName("Baz"));     } } 
like image 117
Jon Skeet Avatar answered Oct 13 '22 06:10

Jon Skeet