使用class.isEnum()还是Enum? [英] Is it better to use class.isEnum() or instanceof Enum?

查看:431
本文介绍了使用class.isEnum()还是Enum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象。我想检查它是否是枚举类型。有两种方法可以实现。

  object.getClass()。isEnum()

 对象instanceof枚举

更好吗?

解决方案

在我看来,对象instanceof枚举更好的原因有几个:




  • 这是非常明显的:这是一个枚举吗?

  • 它不冒险 NullPointerException (如果对象 null ,它只会评估为 false

  • 更短。



我看到使用 isEnum()将是,如果我只能访问对象而不是具体实例。


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.

这篇关于使用class.isEnum()还是Enum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆