How to convert the string value to Enum in Java?

advertisements

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