public
static <T extends Enum<T>> T valueOf(Class<T>
enumType, String name)
Returns
the enum constant of the specified enum type with the specified name.
enum Day{ MON, TUE, WED, THU, FRI, SAT, SUN; public static void main(String args[]){ Class<Day> enumType = Day.class; Enum<Day> dayVal = Enum.valueOf(enumType, "MON"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "TUE"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "WED"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "THU"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "FRI"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "SAT"); System.out.println(dayVal.name()); dayVal = Enum.valueOf(enumType, "SUN"); System.out.println(dayVal.name()); } }
Output
MON TUE WED THU FRI SAT SUN
1.
throws IllegalArgumentException if the specified enum type has
no
constant with the specified name, or the specified class object does
not represent an enum type
enum Day{ MON, TUE, WED, THU, FRI, SAT, SUN; public static void main(String args[]){ Class<Day> enumType = Day.class; Enum<Day> dayVal = Enum.valueOf(enumType, "ABC"); System.out.println(dayVal.name()); } }
Output
Exception in thread "main" java.lang.IllegalArgumentException: No enum constat Day.ABC at java.lang.Enum.valueOf(Enum.java:236) at Day.main(Day.java:13)
2. throws
NullPointerException if enumType or name is null
enum Day{ MON, TUE, WED, THU, FRI, SAT, SUN; public static void main(String args[]){ Class<Day> enumType = Day.class; Enum<Day> dayVal = Enum.valueOf(enumType, null); System.out.println(dayVal.name()); } }
Output
Exception in thread "main" java.lang.NullPointerException: Name is null at java.lang.Enum.valueOf(Enum.java:235) at Day.main(Day.java:13)
No comments:
Post a Comment