Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example "A"
which would be Blah.A
. How would it be possible to do this?
Is the Enum.valueOf()
the method I need? If so, how would I use this?
java.lang.Enum
defines several useful methods, which is available to all enumeration type in Java:name()
method to get name of any Enum constants. String literal used to write enum constants is their name.values()
method can be used to get an array of all Enum constants from an Enum type.valueOf()
method to convert any String to Enum constant in Java, as shown below.In this code snippet,
valueOf()
method returns an Enum constant Gender.MALE, calling name on that returns"MALE"
.Adding on to the top rated answer, with a helpful utility...
valueOf()
throws two different Exceptions in cases where it doesn't like its input.IllegalArgumentException
NullPointerExeption
If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...
So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.
Use it like this:
Using
Blah.valueOf(string)
is best but you can useEnum.valueOf(Blah.class, string)
as well.Another utility capturing in reverse way. Using a value which identify that Enum, not from its name.
Example:
EnumUtil.from(Foo.class, "drei")
returnsFoo.THREE
, because it will usegetValue
to match "drei", which is unique public, not final and not static method in Foo. In case Foo has more than on public, not final and not static method, for example,getTranslate
which returns "drei", the other method can be used:EnumUtil.from(Foo.class, "drei", "getTranslate")
.What about?