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?
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).
The advantage of an enum is that they are a strongly typed value. There are no advantages to using strings.
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.
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.
In my opinion object instanceof Enum
is better for several reasons:
NullPointerException
(if object
is null
, it will just evaluate to 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With