Home > DeveloperSection > Forums > Convert a String to an enum in Java
Samuel Fernandes
Samuel Fernandes

Total Post:155

Posted on    May-08-2015 1:17 AM

 Java Java  String 

 1 Reply(s)
 515  View(s)
Rate this:
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?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-08-2015 6:50 AM

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

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.  

You can use Enum.valueOf(Blah.class, string) as well.  

If you don't want to write your own utility use Google's guava library:
Enums.getIfPresent(Blah.class, "A")  

Don't want to miss updates? Please click the below button!

Follow MindStick