你真的瞭解Java中的Instanceof嗎?__Java

來源:互聯網
上載者:User

instanceof 是一個簡單的二元操作符, 它是用來判斷一個對象是否是一個類執行個體的

boolean b1 = "Sting" instanceof Object;
b1為true 因為String是Object的子類

boolean b2 = new String() instanceof String;
b2為true

boolean b3 = new Object() instanceof String;
b3為false Object是父類

boolean b4 = 'A' instanceof Character;
編譯不通過 ‘A’在此處視為基礎資料型別 (Elementary Data Type)char,instanceof操作符只能用作對象的判斷

boolean b5 = null instanceof String;
b5為false 這是instanceof 特 有 的 規 則 : 若左運算元為null, 結果就直接返回false, 不再運算右運算元是什麼類。

boolean b6 = (String)null instanceof String;
b6為false 即使類型轉換還是個 null

boolean b7 = new Date() instanceof String;
編譯不通過 instanceof 操作符的左右運算元必須有繼承或實現關係,否則編譯出錯

boolean b8 = new GenericClass<String>().isDateInstance("");
class GenericClass<T>{
public boolean isDateInstance(T t){
return t instanceof Date;
}

編譯通過,b8為false 因為用了泛型,所以位元組碼的時候T就是Object類型啦,此處t instanceof Date等價於Object instance of Date。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.