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

发布于 2024-12-28 15:07:14 字数 321 浏览 2 评论 0原文

我想检查 java.lang.reflect.Type 实例是否代表 Emum 对象。

我可以使用 == 比较来检查它是否是特定类的实例,例如:

type == String.class // works

但这似乎不适用于 Enum 类:

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

...这是有道理的,因为该实例是特定枚举的实例,但我想检查该类型是否适用于任何枚举。

有人可以向我解释一下如何判断类型是否是枚举的显而易见的事情吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娇柔作态 2025-01-04 15:07:14
if(type instanceof Class && ((Class<?>)type).isEnum())
if(type instanceof Class && ((Class<?>)type).isEnum())
冬天旳寂寞 2025-01-04 15:07:14

Class.isEnum() 会为你做这件事。

请参阅 Oracle 文档

Class.isEnum() will do it for you.

Refer to Oracle Doc

一曲琵琶半遮面シ 2025-01-04 15:07:14

为什么不使用 .equals 方法来比较这种类型的比较。 == 主要用于原始类型。

type.equals(Enum.class)

或者也许您需要比较您自己的课程。

type.equals(MyClass.class)

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)
も星光 2025-01-04 15:07:14
if(type instanceof Class && (Class)type.getClass().isEnum()) {...}
if(type instanceof Class && (Class)type.getClass().isEnum()) {...}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文