假设我有一个枚举,即:
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()
将任何对象转换为字符串。(该字符串是否有意义取决于实现;)
使用不同的枚举构造。像这样的东西(我在我的代码中使用它):
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 的字符串表示形式。
Enum.valueOf(FooBar.class, nameOfEnum);
nameOfEnum
字符串“一”、“二”等在哪里?
尝试以下代码:
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);
}
}
}