Suppose I have an Enum as:
com.mypackage.enums
public enum Days {
MONDAY,
TUESDAY,
WEDNESDAY
}
Now somewhere I know that I need to get enum MONDAY from a runtime string provided as "MONDAY". I also know that this enum lies in com.mypackage.enums.Days
How can I do this? With or without reflection?
EDIT: Both the string "MONDAY" and Class com.mypackage.enum.Days are determined at Runtime. Class is provided as object of Class and not as string.
You can use Enum.valueOf(Class, String)
:
import java.util.*;
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class Test {
public static void main(String[] args) throws Exception {
String className = "Day";
String name = "SATURDAY";
// Note use of raw type
Class clazz = Class.forName(className);
Enum value= Enum.valueOf(clazz, name);
System.out.println("Parsed: " + value);
}
}
Now this uses the raw Class
type, which is never terribly nice - but I'm not sure what the better alternative is here. Fundamentally generics is about situations where you know the types at compile-time, and you don't here.
You might want to add a bit of validation yourself, and then suppress the warning about raw types just for this piece of code.
See more on this question at Stackoverflow