简体   繁体   中英

How to convert string value into Enum in Java?

In my Java Program have Enum class like..

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 ..

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

My HibernateVO class is ..

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)

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

but it is show error..

So how to convert my String value into enum class type?

Use the valueOf method on the Enum class.

DemoType demoType =   DemoType.valueOf("DAILY")

It'll throw an IllegalArgumentException should the string argument provided be invalid. Using your example

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

The line above will throw an IllegalArgumentException because HOURLY is not part of your DemoType

This may help you to understand how enum types work.

Say, This is my enum class.

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

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:

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:

@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. Make sure that the String value is the same as declared enum. For example

    DemoType dt = DemoType.valueOf("DAILY")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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