使用Enum变量切换字符串

编程入门 行业动态 更新时间:2024-10-19 14:46:26
本文介绍了使用Enum变量切换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有不同值的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变量切换字符串

本文发布于:2023-11-22 06:24:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   变量   Enum

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!