Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an enum value from a string value in Java

Tags:

java

enums

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?

like image 632
Malachi Avatar asked Mar 02 '09 22:03

Malachi


People also ask

How do you create an enum from a String?

You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.

Can we convert String to enum in Java?

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.


1 Answers

Yes, Blah.valueOf("A") will give you Blah.A.

Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.

The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

like image 84
Michael Myers Avatar answered Nov 18 '22 07:11

Michael Myers