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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:20:53  来源:igfitidea点击:

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

javaenums

提问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 Enumis 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(if objectis null, it will just evaluate to false)
  • It's shorter.
  • 很明显这里问的是什么:“这是一个枚举”吗?
  • 它没有风险NullPointerException(如果objectnull,它只会评估为false
  • 它更短。

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

我认为使用的唯一原因isEnum()是我只能访问Class对象而不是具体实例。