Checking if a class is java.lang.Enum

Jose L Martinez-Avial picture Jose L Martinez-Avial · Nov 12, 2010 · Viewed 49k times · Source

I'm trying to know if a class is an Enum, but I think I'm missing something:

if (test.MyEnum.class instanceof Enum<?>.class)
 obj = resultWrapper.getEnum(i, test.MyEnum.class);
else 
 obj = resultWrapper.getObject(i);

It gives me an error saying that Enum.class is not valid. So how I can check if a class is a Enum? I'm pretty sure it is possible to determine that, I'm just unable to get it.

Thanks

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Nov 12, 2010

The correct syntax would be:

Enum.class.isAssignableFrom(test.MyEnum.class)

but for enums, here is a more convenient method:

if (someObject.getClass().isEnum()))

Update: for enum items with a body (e. g. that override methods), this won't actually work. In that case, use

if (someObject instanceof Enum<?>)

Reference: