Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable?

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.

Leave a Comment