這篇文章主要介紹Java中instanceof關鍵字和isInstance()方法的區別有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
instanceof關鍵字和isInstance()方法都是用于檢查對象的類,都返回一個布爾值。但是當我們想要動態檢查對象的類時,主要區別就出現了。在這種情況下,isInstance()方法將起作用,而無法通過instanceof運算符來實現這一點。
下面我們通過示例來具體看看instanceof關鍵字和isInstance()方法之間的區別。
使用instanceof關鍵字來檢查對象的類
public class Test { public static void main(String[] args) { Integer i = new Integer(5); // 當i是Integer類的實例時,輸出true System.out.println(i instanceof Integer); } }
輸出:
true
現在,如果我們想在運行時檢查對象的類,那么我們必須使用isInstance()方法。
public class Test { // 此方法告訴我們對象是否是以字符串“c”形式傳遞名稱的類實例。 public static boolean fun(Object obj, String c) throws ClassNotFoundException { return Class.forName(c).isInstance(obj); } public static void main(String[] args) throws ClassNotFoundException { Integer i = new Integer(5); // 當i是Integer類的實例時,輸出true boolean b = fun(i, "java.lang.Integer"); // 因為i不是String類的實例,所以輸出false boolean b1 = fun(i, "java.lang.String"); //當integer類擴展number類時,如果我也是number類的實例,則輸出true。 boolean b2 = fun(i, "java.lang.Number"); System.out.println(b); System.out.println(b1); System.out.println(b2); } }
輸出:
true false true
注:如果我們使用未實例化的其他類檢查對象,則instanceof關鍵字會拋出編譯時錯誤(不兼容的條件操作數類型)。
public class Test { public static void main(String[] args) { Integer i = new Integer(5); //報錯,因為類型不兼容:Integer不能轉換為String System.out.println(i instanceof String); } }
輸出:
demo.java:10: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^ 1 error
以上是Java中instanceof關鍵字和isInstance()方法的區別有哪些的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。