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

2019-02-05 17:11发布

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

4条回答
ら.Afraid
2楼-- · 2019-02-05 17:44

Why don't you use .equals method to compare this type of comparisons. == is mostly used for primitive types.

type.equals(Enum.class)

or maybe you will need compare your own classes.

type.equals(MyClass.class)
查看更多
Ridiculous、
3楼-- · 2019-02-05 17:50
if(type instanceof Class && ((Class<?>)type).isEnum())
查看更多
做自己的国王
4楼-- · 2019-02-05 17:53
if(type instanceof Class && (Class)type.getClass().isEnum()) {...}
查看更多
手持菜刀,她持情操
5楼-- · 2019-02-05 17:58

Class.isEnum() will do it for you.

Refer to Oracle Doc

查看更多
登录 后发表回答