1. Introduction
An enum is a special class in Java that represents a group of constants. In this short tutorial, we are going to present how to get enum value using String.
2. The problem: Get enum using String value
Let's say we have the following enum Alphabet
:
We want to find the enum value of a String, for example, "A" which would be Alphabet.A
.
3. Solution1: Use Enum.valueOf(...)
method
Use Alphabet.valueOf(str)
method.
This method returns the enum with the specified name. The name must match exactly an identifier. For example to get Alphabet.A
we need to use Alphabet.valueOf("A")
.
Note that if the specified enum type has no constant with the specified name the IllegalArgumentException
will the thrown.
This could happen for:
Alphabet.valueOf("A ")
- note space at the end,Alphabet.valueOf("9")
- no such contant inAlphaget
enum,Alphabet.valueOf("a")
- method is case sensitive.
4. Solution2: Filtering enum values
You can also manually filter enum values from specified type like in the following example:
In this example we used String.equalsIgnoreCase(...)
to compare specified String with enum values in case-insensitive way.
Now to find Alphabet.A
we can use this method like in the following snippet:
The al
variable will be equal to Alphabet.A
5. Solution3: Checking enum values without throwing an exception
To check if enum contains constant A
without throwing an exception we can use Guava
library.
In the following code we used Enums
utility class from Guava
:
The getIfPresent(...)
method will return Optional.empty()
if Alphabet
doesn't have A
value.
You can also implement this method on your own in Plain Java:
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}