簡體   English   中英

如何從字符串中獲取枚舉值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM