29

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?

java
  • 473
  • 3
  • 9
  • 15
  • 1
    possible duplicate of [Java - Convert String to enum](http://stackoverflow.com/questions/604424/java-convert-string-to-enum) – tashuhka Nov 20 '14 at 14:17

5 Answers5

58

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

kolossus
  • 20,559
  • 3
  • 52
  • 104
  • 1
    please.. i want some more clarification. – java Jul 05 '13 at 04:25
  • If the drop down on the UI is populated using the Enum then this should not be a problem. However as a practice one needs to add validation on the data received from the UI before performing the business logic. – ashoka Jul 05 '13 at 04:35
9

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
   }
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • 1
    It works. But it is too heavy weight. If so, I cannot see the benefit of enum compared to plain class. – Chao Dec 20 '16 at 08:07
4

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
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • 2
    Returning null propagates null checking throughout the API which can easily be avoided. Instead add a UNKNOWN value to the enum to be returned in the unmatched case. – i3ensays Sep 01 '17 at 15:42
1

Using Spring's TypeConverterSupport you can resolve string property to enum instance like that:

@Value("${enum.type}") 
MyEnum enum;
Łukasz Chorąży
  • 506
  • 1
  • 6
  • 23
0

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")
ashoka
  • 651
  • 6
  • 10