简体   繁体   English

如何检查java.lang.reflect.Type是否为Enum

[英]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. 我想检查java.lang.reflect.Type实例是否代表Emum对象。

I can check whether it's an instance of a specific class using == comparisons eg: 我可以使用==比较来检查它是否是特定类的实例,例如:

type == String.class // works

but this doesn't seem to work for the Enum class: 但这对Enum类似乎不起作用:

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 有人可以向我解释如何判断Type是否是枚举请

if(type instanceof Class && ((Class<?>)type).isEnum())

Class.isEnum() will do it for you. Class.isEnum()会为你做。

Refer to Oracle Doc 请参阅Oracle Doc

Why don't you use .equals method to compare this type of comparisons. 为什么不使用.equals方法来比较这种类型的比较。 == is mostly used for primitive types. ==主要用于原始类型。

type.equals(Enum.class)

or maybe you will need compare your own classes. 或者您可能需要比较自己的课程。

type.equals(MyClass.class)
if(type instanceof Class && (Class)type.getClass().isEnum()) {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM