将字符串转换为等效枚举值 [英] Convert String to equivalent Enum value

查看:99
本文介绍了将字符串转换为等效枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用Java将 String 转换为枚举中的等效值。 / p>

我当然可以使用一个大的 if-else 语句,但是如果可能,我想避免这种情况



鉴于此文档:



http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html



我不太希望这可能没有ifs或case语句。

解决方案

希望你意识到, java.util.Enumeration 不同于Java 1.5

您可以使用 YourEnum



因此,如果您的枚举被定义如下:

 公开枚举日{
星期日,星期一,星期四,星期四,
THURSDAY,FRIDAY,SATURDAY
}

您可以这样做:

  String day =SUNDAY; 

Day dayEnum = Day.valueOf(day);


Is it possible for me to convert a String to an equivalent value in an Enumeration, using Java.

I can of course do this with a large if-else statement, but I would like to avoid this if possible.

Given this documentation:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html

I am not too hopeful that this is possible without ifs or a case statement.

解决方案

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

Thus if your enum is defined as so:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}

You could do this:

String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

这篇关于将字符串转换为等效枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆