instanceof Vs getClass( )

后端 未结 4 1841
一向
一向 2020-12-02 04:36

I see gain in performance when using getClass() and == operator over instanceOf operator.

Object  str = new Integer(\"         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-02 05:01

    Do you want to match a class exactly, e.g. only matching FileInputStream instead of any subclass of FileInputStream? If so, use getClass() and ==. I would typically do this in an equals, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.

    Otherwise, use instanceof. Note that with getClass() you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException, whereas instanceof will just return false if the first operand is null.

    Personally I'd say instanceof is more idiomatic - but using either of them extensively is a design smell in most cases.

提交回复
热议问题