开发者

Is it better to use class.isEnum() or instanceof Enum?

I have an object. I want to check to see if it is of type enum. There are two ways to do this.

object.getClass().isEnum()

or

object instanceof Enum
开发者_如何学运维

Is one better?


In my opinion object instanceof Enum is better for several reasons:

  • It is very obvious what is asked here: "is this an enum"?
  • It doesn't risk a NullPointerException (if object is null, it will just evaluate to false)
  • It's shorter.

The only reason I'd see for using isEnum() would be if I only have access to the Class object and not to a concrete instance.


You need to use the latter (object instanceof Enum) because the former may not work with enum constants with constant-specific class bodies.

For example, for this enum type:

enum MyEnum {
    FOO { }
}

The expression MyEnum.FOO.getClass().isEnum() returns false.

If you want to check if an object is a enum constant without instanceof Enum, you have to use this (much more complicated) expression:

static boolean isEnum(Object obj) {
    Class<?> cls = obj.getClass();
    Class<?> superCls = cls.getSuperclass();
    // Be careful, Object.class.getSuperclass() returns null
    return cls.isEnum() || (superCls != null && superCls.isEnum());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜