检查类是否为 java.lang.Enum

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4166488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:13:55  来源:igfitidea点击:

Checking if a class is java.lang.Enum

javaenumsinstanceof

提问by Jose L Martinez-Avial

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.

它给了我一个错误,说 Enum.class 无效。那么我如何检查一个类是否是一个 Enum 呢?我很确定可以确定,我只是无法得到它。

Thanks

谢谢

采纳答案by Sean Patrick Floyd

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:

参考:

回答by Roman

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

如果您在谈论 Java 5 新功能 - enum(实际上并不是很新),那么这就是要走的路:

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

...
}

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

如果Enum是您的自定义类,那么只需检查obj instanceof Enum.