When should and shouldn't instanceof be used?

后端 未结 5 621
情书的邮戳
情书的邮戳 2020-12-09 10:50

I have gone through various articles, but I still do not know why instanceof should not be used. Kindly let me know your thoughts.

相关标签:
5条回答
  • 2020-12-09 11:07

    Using instanceof when overriding Object's equals method is necessary, seeing as two objects cannot be equal if they are of different types. I've rarely come accross another situation where instanceof is required - perhaps if downcasting is required but a ClassCastException may be thrown.

    0 讨论(0)
  • 2020-12-09 11:08

    Casting from a base type to a derived type is a bad thing. If you use instandof that way, it's considered bad design because hard to maintain and read. See http://www.javapractices.com/topic/TopicAction.do?Id=31.

    Using instanceof for equals() because you have an object that should be your type, that's good practice.

    0 讨论(0)
  • 2020-12-09 11:21

    When you know the object being passed then you need not use it. If there is any ambiguity involved (like two classes implementing the same interface) then it is advised to use instanceof before proceeding further.

    0 讨论(0)
  • 2020-12-09 11:24

    I find a need to use instanceof hints at bad design. It's a sure sign that a big, complex switch-style construct will follow. Most other times I see it used, we should use polymorphism rather than instanceof. See the Strategy pattern. (relevant examples of use)

    The only time I find I need to use it is when implementing equals(Object o).

    0 讨论(0)
  • 2020-12-09 11:26

    One good use-case would be checking for marker interfaces like RandomAccess.

    0 讨论(0)
提交回复
热议问题