使用Enum变量切换字符串 [英] Switch String with Enum variables
问题描述
我有一个具有不同值的Enum,并且想要切换一个字符串变量。现在,我碰壁试图将Enum值转换为Strings,可以用作大小写常量。
I have got an Enum with different values and want to switch a string variable. Now I hit a wall trying to convert the Enum values to Strings, that I can use as case constant.
我的最佳尝试是将Enum转换为String数组,但该开关似乎不接受数组值作为大小写常量。 (IntelliJ说:需要常量表达式)
My best try was to convert the Enum to a String array, but the switch doesn't seem to accept array values as a case constant. (IntelliJ says: "constant expression required")
Enum myEnum = {FOO, BAR}
String input = "foo"
final String[] constant = Arrays.stream(myEnum.values()).map(Enum::name).toArray(String[]::new);
//converts Enum to String[]; made it final, so it is "constant"
switch (input) {
case constant[0]:
System.out.println("foo");
break;
case constant[1]:
System.out.println("bar");
break;
}
是否有一种优雅的方法可以使此切换依赖于枚举?
Is there an elegant way to make this switch depend on the Enum?
推荐答案
您不应该转换它,因为不需要它。另外,您的代码甚至都不会编译,因为 case
是Java中的保留关键字。
You shouldn't convert it because it isn't needed. Also, your code won't even compile because case
is a reserved keyword in Java.
您应该使用看看 Enum
的 valueOf
方法。
You should take a look at the valueOf
method of an Enum
.
您的代码如下所示:
public enum MyEnum {FOO, BAR}
//method
String input = "foo";
MyEnum niceFound = MyEnum.valueOf(input.toUpperCase());
这将返回 FOO
但可以抛出 IllegalArgumentException
当给定值不作为类型出现时。
That will return FOO
but can throw an IllegalArgumentException
when the given value isn't present as type.
这篇关于使用Enum变量切换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!