java - How to get Enum when it's string representation and type are known at Runtime? -
suppose have enum as:
com.mypackage.enums public enum days { monday, tuesday, wednesday }
now somewhere know need enum monday runtime string provided "monday". know enum lies in com.mypackage.enums.days
how can this? or without reflection?
edit: both string "monday" , class com.mypackage.enum.days determined @ runtime. class provided object of class , not string.
an alternative @jonskeet solution not involve raw types (only unchecked cast):
static <t extends enum<t>> enum<t> getvalue(string classname, string name) throws classnotfoundexception { @suppresswarnings("unchecked") class<t> clazz = (class<t>) class.forname(classname); return enum.valueof(clazz, name); } public static void main(string[] args) throws exception { string classname = "day"; string name = "saturday"; // note use of raw type system.out.println("parsed: " + getvalue(classname, name)); }
of course if have class
object, can use
enum.valueof(classobj, name);
Comments
Post a Comment