Over the years, I've tried to avoid instanceof
whenever possible. Using polymorphism or the visitor pattern where applicable. I suppose it simply eases maintenance in some situations... Are there any other drawbacks that one should be aware of?
I do however see it here and there in the Java libraries so I suppose it has its place? Under what circumstances is it preferable? Is it ever unavoidable?
It's definitely has its place in a stock implementation of equals
. E.g.
public boolean equals ( Object o )
{
if ( this == o )
{
return true;
}
if ( ! (o instanceof MyClass) )
{
return false;
}
// Compare fields
...
}
One neat thing to know about instanceof is that its LHS can be null
and in that case the expression evaluates to false
.