getClass() can not work the same as .class

Code_Control_jxie0755 :

If I have a enum class:

enum WorkDays {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}

And I have:

WorkDays day1 = WorkDays.valueOf("MONDAY");

for the method: public static <T extends Enum<T>> T valueOf​(Class<T> enumType, String name)

If I force to check the enumType, I can write:

WorkDays day2 = Enum.valueOf(WorkDays.class,"TUESDAY");

But it can't be:

WorkDays day2b = Enum.valueOf(day1.getClass(), "MONDAY");

Most people say that Object.class should be called by a class, but getClass() should be called by an Instance, but it seems that the difference is more than just this?

assylias :

getClass returns a Class<? extends WorkDays> but Enum.valueOf expects its first argument to be a Class<WorkDays>.

To get the correct class type, i.e. Class<WorkDays>, you can use the getDeclaringClass method:

WorkDays day2b = Enum.valueOf(day1.getDeclaringClass(), "MONDAY");

Now it happens that day1 is a Workdays, so you could also cast to the correct type:

WorkDays day2b = Enum.valueOf((Class<WorkDays>) day1.getClass(), "MONDAY");

Note that this cast will fail if MONDAY has a body (for example if it overrides a method of the enum).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158844&siteId=1