Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if java.lang.reflect.Type is an Enum

I want to check whether a java.lang.reflect.Type instance represents an Emum object or not.

I can check whether it's an instance of a specific class using == comparisons e.g:

type == String.class // works 

but this doesn't seem to work for the Enum class:

type == Enum.class // doesn't work 

... this makes sense as the instance would be of a specific enum but I would like to check whether the type is for any enum or not.

Could someone explain the obvious to me of how to tell whether the Type is an enum or not please

like image 943
Edd Avatar asked Jan 23 '12 15:01

Edd


People also ask

How do you check if a type is an 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. It is a read-only property.

How do I find my enum instance?

if (obj. getClass(). isEnum()) { ... } If Enum is your custom class, then just check that obj instanceof Enum .

What is Java Lang reflect type?

Provides classes that are fundamental to the design of the Java programming language. java.lang.reflect. Provides classes and interfaces for obtaining reflective information about classes and objects.


2 Answers

if(type instanceof Class && ((Class<?>)type).isEnum()) 
like image 128
jtahlborn Avatar answered Sep 18 '22 13:09

jtahlborn


Class.isEnum() will do it for you.

Refer to Oracle Doc

like image 28
Sunil Avatar answered Sep 19 '22 13:09

Sunil