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?
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.
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.
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:
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")); } }
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