Different ways to check the type of an object in java?
Beware: instanceof
Returns true also if your object is a subclass MyClass
, or if it implements an interface (this is usually what you're interested in - if you remember the concept of the "IS A" PMO)
See also about Class.isAssignableFrom()
, similar to instanceof
but slightly more powerful.
a source to share
As others say, instanceof
does not have the same functionality as equals
.
At another point when it comes to this issue in code, using the Visitor- pattern is clean (though not the smallest in the line of code). A nice benefit is that after the UI has been set up for a set of classes, this can be reused in all other places that all / some / some different class extensions should handle.
a source to share