Wednesday 18 October 2017

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

itemprop="text">

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?



Answer




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, href="http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html"
rel="noreferrer">Dialog.ModalityType shows both
methods.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...