Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a class is java.lang.Enum

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

like image 261
Jose L Martinez-Avial Avatar asked Nov 12 '10 16:11

Jose L Martinez-Avial


People also ask

How do you know if a class is enum?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false.

What is Java Lang enum?

Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java. Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable.

Can you use == for enums Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.


2 Answers

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:

  • Class.isEnum()
like image 123
Sean Patrick Floyd Avatar answered Oct 10 '22 15:10

Sean Patrick Floyd


If you're talking about Java 5 new feature - enum (it's not very new actually), then this is the way to go:

if (obj.getClass().isEnum()) {  ... } 

If Enum is your custom class, then just check that obj instanceof Enum.

like image 42
Roman Avatar answered Oct 10 '22 16:10

Roman