Checking if a class is java.lang.Enum

廉价感情. 提交于 2019-12-20 10:14:34

问题


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.

Thanks


回答1:


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:

  • Class.isEnum()



回答2:


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

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

...
}

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



来源:https://stackoverflow.com/questions/4166488/checking-if-a-class-is-java-lang-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!