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
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.public class EnumDemo06 {
public static void main(String args[]) {
Gender fromString = Gender.valueOf("MALE");
System.out.println("Gender.MALE.name() : " + fromString.name());
}
private enum Gender {
MALE, FEMALE;
}
}
Output:
Gender.MALE.name() : MALE
In this code snippet, valueOf()
method returns an Enum constant Gender.MALE, calling name on that returns "MALE"
.