[英]How do I get an enum value from a string?
说我有一个枚举,即:
public enum FooBar {
One, Two, Three
}
我想获取一个字符串的对应枚举值,假设为“ Two”,并获取FooBar.Two。
如何用Java做到这一点? Enum.ValueOf()
似乎没有关联。
我有字符串“ Two”,我想要这个值。
为此,请使用valueOf
例如
MyEnum me = MyEnum.valueOf("Two");
要么
MyEnum me = Enum.valueOf(MyEnum.class, "Two");
Enum.ValueOf()似乎没有关联。
看来这正是您想要的。
您可以使用
String s = myEnum.toString();
要么
String s = myEnum.name();
您可以使用toString()
将任何对象转换为String。 (String是否有意义不取决于实现;)
使用不同的枚举构造。 像这样的东西(我在我的代码中使用它):
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;
}
}
getDisplayName()
将返回ENUM的String表示形式。
Enum.valueOf(FooBar.class, nameOfEnum);
其中, nameOfEnum
是字符串“ One”,“ Two”等。
尝试以下代码:
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.