Reputation: 321
I'm trying to pass an enum constant as an argument to a method via reflection. Here is a simple example that demonstrates a very simplified version of my problem. (Assume I must use reflection)
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class Main {
public void print(Day d) {
System.out.println(d);
}
public static void main(String[] args) throws Exception
{
Class<?> cl = Class.forName("Day");
Field field = cl2.getDeclaredField("MONDAY");
print(_what_to_pass_here?)
}
}
How do I do it?
Thanks,
Upvotes: 1
Views: 351
Reputation: 315
Try java.lang.reflect.Field.get(Object obj)
:
Day day = (Day) field.get(cl);
print(day);
Upvotes: 1
Reputation: 50716
You don't need to access the field directly. Use Enum.valueOf()
:
Enum.valueOf(cl.asSubclass(Day.class), "MONDAY")
But it's hard to see why you couldn't use Day.class
directly. It might help to elaborate on your use case.
Upvotes: 5