How do I "valueOf" an enum given a class name?
Posted
by stevemac
on Stack Overflow
See other posts from Stack Overflow
or by stevemac
Published on 2010-06-09T06:29:16Z
Indexed on
2010/06/09
6:32 UTC
Read the original article
Hit count: 139
Lets say I have a simple Enum called Animal defined as:
public enum Animal {
CAT, DOG
}
and I have a method like:
private static Object valueOf(String value, Class<?> classType) {
if (classType == String.class) {
return value;
}
if (classType == Integer.class) {
return Integer.parseInt(value);
}
if (classType == Long.class) {
return Long.parseLong(value);
}
if (classType == Boolean.class) {
return Boolean.parseBoolean(value);
}
// Enum resolution here
}
What can I put inside this method to return an instance of my enum where the value is of the classType?
I have looked at trying:
if (classType == Enum.class) {
return Enum.valueOf((Class<Enum>)classType, value);
}
But that doesn't work.
© Stack Overflow or respective owner