简体   繁体   English

如何从字符串中获取枚举值?

[英]How do I get an enum value from a string?

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. 我想获取一个字符串的对应枚举值,假设为“ Two”,并获取FooBar.Two。

How can I do this in Java? 如何用Java做到这一点? Enum.ValueOf() does not seem to be related. Enum.ValueOf()似乎没有关联。

I have the string 'Two' and I want the value. 我有字符串“ Two”,我想要这个值。

To do this you use valueOf eg 为此,请使用valueOf例如

MyEnum me = MyEnum.valueOf("Two");

or 要么

MyEnum me = Enum.valueOf(MyEnum.class, "Two");

Enum.ValueOf() does not seem to be related. Enum.ValueOf()似乎没有关联。

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. 您可以使用toString()将任何对象转换为String。 (Whether that String makes sense of not depends on the implementation ;) (String是否有意义不取决于实现;)

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. getDisplayName()将返回ENUM的String表示形式。

Enum.valueOf(FooBar.class, nameOfEnum);

其中, nameOfEnum是字符串“ One”,“ Two”等。

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);
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM