Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

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?

like image 259
Amir Raminfar Avatar asked Aug 11 '11 19:08

Amir Raminfar


People also ask

Is enum better than constant?

Difference between Enums and Classes The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Are Enums better than strings?

The advantage of an enum is that they are a strongly typed value. There are no advantages to using strings.

When should Enums be used?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

How are Java Enums more powerful than integer constants?

Java Enums provide many features that integer constants cannot. Enums can be considered as final classes with a fixed number of instances. Enums can implement interfaces but cannot extend another class. While implementing the strategy pattern, we can use this feature of Enums.


1 Answers

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.

like image 135
Joachim Sauer Avatar answered Sep 18 '22 11:09

Joachim Sauer