Java中instanceof和isInstance的具體區別

來源:互聯網
上載者:User

標籤:模糊   operator   描述   method   UI   post   etc   AC   val   

Java中instanceof和isInstance的具體區別

在Think in Java泛型這一章遇到這個問題,一些部落格模糊提到了isInstance是instanceof的動態實現,查閱文檔參考SOF上的一些回答如下:

  • obj.instanceof(class)

表示對象obj是否是class類或其子類的對象

  1. 一個對象是自身類的一個對象
  2. 一個對象是自身類父類和介面的一個對象
  3. 所有對象都是Object類的對象
  4. 凡是null有關的都是false
  • class.isInstance(obj)

文檔中這樣描述

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.

即對象obj能否轉化為類class的對象,動態等價於instanceof

  1. 一個對象能轉化為自身類的對象
  2. 一個對象能被轉化為自身類的父類和實現的介面的對象
  3. 所有對象都能轉化為Object類的對象
  4. 凡是null有關的都是false

可見與instanceof用法相同,關鍵在於動態等價

  • 動態等價性
class Father{}class Son extends Father{}public class Test{    public static boolean DynamicEqual(Object fatherObj,Object sonObj){        return fatherObj.getClass().isInstance(sonObj); // pass        // return sonObj instanceof Father; // pass        // return sonObj instanceof (fatherObj.getClass()); //error    }    public static void main(String[] args){        //same using        Father father = new Father();        Son son = new Son();        System.out.println(son instanceof Son); // true        System.out.println(son instanceof Father); // true        System.out.println(son instanceof Object); // true        System.out.println(null instanceof Object); // false        System.out.println();        System.out.println(Son.class.isInstance(son)); // true        System.out.println(Father.class.isInstance(son)); // true        System.out.println(Object.class.isInstance(son)); // true        System.out.println(Object.class.isInstance(null)); // false        System.out.println();        //different using        System.out.println(DynamicEqual(father, son));    }}

對obj.instanceof(class),在編譯時間編譯器需要知道類的具體類型

對class.isInstance(obj),編譯器在運行時才進行類型檢查,故可用於反射,泛型中

參考:

https://stackoverflow.com/questions/8692214/when-to-use-class-isinstance-when-to-use-instanceof-operator

https://stackoverflow.com/questions/15757014/isinstance-instanceof-why-theres-no-generic-way

http://blog.csdn.net/u010002184/article/details/79306195

Java中instanceof和isInstance的具體區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.