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

Mar*_*zar 0 java enums

假设我有一个枚举,即:

public enum FooBar {
  One, Two, Three
}
Run Code Online (Sandbox Code Playgroud)

我想获得一个字符串的相应枚举值,让我们说'两个',然后得到FooBar.Two.

我怎么能用Java做到这一点?Enum.ValueOf()似乎没有相关性.

Pet*_*rey 6

我有字符串'Two',我想要值.

为此,您可以使用valueOfeg

MyEnum me = MyEnum.valueOf("Two");
Run Code Online (Sandbox Code Playgroud)

要么

MyEnum me = Enum.valueOf(MyEnum.class, "Two");
Run Code Online (Sandbox Code Playgroud)

Enum.ValueOf()似乎没有关系.

它似乎正是你想要的.


你可以使用其中之一

String s = myEnum.toString();
Run Code Online (Sandbox Code Playgroud)

要么

String s = myEnum.name();
Run Code Online (Sandbox Code Playgroud)

您可以使用toString()将任何对象转换为String.(String是否理解不取决于实现;)