简体   繁体   English

如何在Java中将字符串值转换为Enum?

[英]How to convert string value into Enum in Java?

In my Java Program have Enum class like.. 在我的Java程序中有Enum类就像..

public enum DemoType{
DAILY, WEEKLY, MONTHLY;
 }

And in my jsp i'm taking values from user like select box and this Jsp called like DemoJspBean .. 在我的jsp中,我从用户那里获取值,如选择框和这个Jsp调用,如DemoJspBean ..

<form:select path="repeatWeektype">
    <form:option value="DAILY" />
    <form:option value="WEEKLY" />
    <form:option value="MONTHLY" />
</form:select>

My HibernateVO class is .. 我的HibernateVO类是..

public class DemoVO{
  @Column(name = "REPEAT_TYPE")
  @Enumerated(EnumType.STRING)
  private RepeatType repeatType;
}

Now i want to insert this value into DB using Hibernate Bean(setter and getter) 现在我想使用Hibernate Bean(setter和getter)将此值插入到DB中

DemoVO demo = new DemoVO();
demo.setRepeatType(demoJspBean.getRepeatWeektype());

but it is show error.. 但它显示错误..

So how to convert my String value into enum class type? 那么如何将我的String值转换为枚举类类型?

Use the valueOf method on the Enum class. Enum类上使用valueOf方法。

DemoType demoType =   DemoType.valueOf("DAILY")

It'll throw an IllegalArgumentException should the string argument provided be invalid. 如果提供的字符串参数无效,它将抛出IllegalArgumentException Using your example 用你的例子

DemoType demoType =  DemoType.valueOf("HOURLY");

The line above will throw an IllegalArgumentException because HOURLY is not part of your DemoType 上面的行将抛出IllegalArgumentException因为HOURLY不是您的DemoType一部分

This may help you to understand how enum types work. 这可以帮助您了解enum类型的工作原理。

Say, This is my enum class. 说,这是我的enum课程。

public enum GetDate {

SUNDAY("1"), MONDAY("2"), TUESDAY("3"), WEDNESDAY("4"), THURSDAY("5"), FRIDAY("6"), SATURDAY("7");
private String code;

private GetDate(String code) {
    this.code = code;
}

public String getCode() {
    return code;
}

public static GetDate getEnum(String code) {

    switch (code) {
        case "1":
            return SUNDAY;
        case "2":
            return MONDAY;
        case "3":
            return TUESDAY;
        case "4":
            return WEDNESDAY;
        case "5":
            return THURSDAY;
        case "6":
            return FRIDAY;
        case "7":
            return SATURDAY;
        default:
            return null;
     }
   }
 }

Following shows how my enum works 以下显示我的enum如何工作

public class MyClass {
public static void main(String[] args) {
    System.out.println("Sunday enum value " + GetDate.SUNDAY);  // enum SUNDAY
    System.out.println("Name of the day assign to 1 " + GetDate.getEnum("1"));  // enum SUNDAY
    System.out.println("Sunday enum value " + GetDate.valueOf("SUNDAY").getCode()); // String code of SUNDAY
    System.out.println("Sunday enum value " + GetDate.valueOf("SUNDAY"));// enum Sunday
   }
}

If for some reason you use a value that does not exist in the enum (using the method DemoType.valueOf() , you'll get an java.lang.IllegalArgumentException . Hey! Wait!, you can iterate into the values: 如果由于某种原因你使用枚举中不存在的值(使用方法DemoType.valueOf() ,你将得到一个java.lang.IllegalArgumentException 。嘿!等等!你可以迭代到值:

public static void main(String[] args) {
    System.out.println(DemoType.convert("DAILY"));
    System.out.println(DemoType.convert("YEARLY"));
}

enum DemoType {
    DAILY, WEEKLY, MONTHLY;
    public static DemoType convert(String str) {
        for (DemoType demoType : DemoType.values()) {
            if (demoType.toString().equals(str)) {
                return demoType;
            }
        }
        return null;
    }
}

The output: 输出:

DAILY
null

Using Spring's TypeConverterSupport you can resolve string property to enum instance like that: 使用Spring的TypeConverterSupport,您可以将字符串属性解析为枚举实例,如下所示:

@Value("${enum.type}") 
MyEnum enum;

You can user DemoType.valueOf() method by passing the string, which will convert it to the DemoType enum corresponding to the string. 您可以通过传递字符串来使用DemoType.valueOf()方法,该字符串将其转换为与字符串对应的DemoType枚举。 Make sure that the String value is the same as declared enum. 确保String值与声明的枚举相同。 For example 例如

    DemoType dt = DemoType.valueOf("DAILY")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM