简体   繁体   中英

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.

How can I do this in Java? Enum.ValueOf() does not seem to be related.

I have the string 'Two' and I want the value.

To do this you use valueOf eg

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

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.

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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