java 使用 class.isEnum() 还是 instanceof Enum 更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7031920/
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
Is it better to use class.isEnum() or instanceof Enum?
提问by Amir Raminfar
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?
一个更好吗?
回答by Joachim Sauer
In my opinion object instanceof Enum
is better for several reasons:
我认为object instanceof Enum
更好的原因有几个:
- It is very obvious what is asked here: "is this an enum"?
- It doesn't risk a
NullPointerException
(ifobject
isnull
, it will just evaluate tofalse
) - It's shorter.
- 很明显这里问的是什么:“这是一个枚举”吗?
- 它没有风险
NullPointerException
(如果object
是null
,它只会评估为false
) - 它更短。
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.
我认为使用的唯一原因isEnum()
是我只能访问Class
对象而不是具体实例。