Sami Hailu
Sami Hailu

Reputation: 321

How to pass enum argument via reflection in Java

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

Answers (2)

papandreus
papandreus

Reputation: 315

Try java.lang.reflect.Field.get(Object obj):

Day day = (Day) field.get(cl);
print(day);

Upvotes: 1

shmosel
shmosel

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

Related Questions