Reputation: 35
Say I have an enum which that is:
public enum FooBar {
One, Two, Three
}
I would like to get the corresponsing enum value of a string, lets say 'Two', and get FooBar.Two.
How can I do this in Java? Enum.ValueOf()
does not seem to be related.
Upvotes: 0
Views: 178
Reputation: 13066
Try following Code:
enum FooBar
{
One,Two,Three;
}
public class EnumByName
{
public static void main(String stp[])
{
String names[] = {"One","Two","Three"};
for (String name : names)
{
FooBar fb = Enum.valueOf(FooBar.class,name);
System.out.println(fb);
}
}
}
Upvotes: 0
Reputation: 5547
Enum.valueOf(FooBar.class, nameOfEnum);
Where nameOfEnum
is the String "One", "Two", etc.
Upvotes: 1
Reputation: 533880
I have the string 'Two' and I want the value.
To do this you use valueOf
e.g.
MyEnum me = MyEnum.valueOf("Two");
or
MyEnum me = Enum.valueOf(MyEnum.class, "Two");
Enum.ValueOf() does not seem to be related.
It appears it's exactly what you want.
You can use either
String s = myEnum.toString();
or
String s = myEnum.name();
You can use toString()
to turn any object in to a String. (Whether that String makes sense of not depends on the implementation ;)
Upvotes: 6
Reputation: 4324
Use a different Enum construction. Something like this (i use it in my code):
enum ReportTypeEnum {
DETAILS(1,"Details"),
SUMMARY(2,"Summary");
private final Integer value;
private final String label;
private ReportTypeEnum(int value, String label) {
this.value = value;
this.label = label;
}
public static ReportTypeEnum fromValue(Integer value) {
for (ReportTypeEnum e : ReportTypeEnum.values()) {
if (e.getValue().equals(value)) {
return e;
}
}
throw new IllegalArgumentException("Invalid Enum value = "+value);
}
public String getDisplayName() {
return label;
}
public Integer getValue() {
return value;
}
}
The getDisplayName()
will return the String representation of the ENUM.
Upvotes: 1