17 March 2014

Converting String to Enum instance in Java

Sample Exception callstack:

java.lang.IllegalArgumentException: No enum const class oracle.apps.xx.xx.xx.xx.CustomCriteriaAdapter$vclist.__DefaultViewCriteria__
     at java.lang.Enum.valueOf(Enum.java:196)
     at oracle.apps.xx.xx.xx.xx.CustomCriteriaAdapter$vclist.valueOf(CustomCriteriaAdapter.java:12)
     at oracle.apps.xx.xx.xx.xx.CustomCriteriaAdapter.getCriteriaClause(CustomCriteriaAdapter.java:23)
     at oracle.jbo.common.CommonCriteriaAdapter.getCriteriaClause(CommonCriteriaAdapter.java:193)
     at oracle.jbo.CriteriaClauses.buildCriteriaClauses(CriteriaClauses.java:86)

Resolution:
Whenever an ENUM is complied in Java, two static methods are added by compiler called valueOf() and values(). We can use valueOf() method to convert any String value to ENUM. For example lets say we have an ENUM called Weekdays.

package net.viralpatel.java.enum;
 
public enum Weekdays {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
Now we want to get an instance of Weekdays enum from string values lets say “Monday”, “Tuesday” etc. We can get this as follow:

Weekdays weekday = Weekdays.valueOf("Monday");
System.out.println(weekday);
Output:
Monday

One thing we need to take care here is if we pass an invalid string to valueOf() method like “XYZ”, the method will give a runtime exception.

Weekdays weekday = Weekdays.valueOf("XYZ");
System.out.println(weekday);
Output:

Exception in thread "main" java.lang.IllegalArgumentException: 
        No enum const class net.viralpatel.java.enum.Weekdays.XYZ
    at java.lang.Enum.valueOf(Enum.java:192)

No comments:

Post a Comment