obj instanceof Type:判斷 obj 所引用對象是否為 Type(類、接口、父類、泛型原始類型)的實例。null 檢查永遠返回 false。
interface IObject {}
class Foo implements IObject {}
class Test extends Foo {}
public class Demo {
public static void main(String[] args) {
IObject obj = new Test();
System.out.println(obj instanceof Object); // true
System.out.println(obj instanceof Foo); // true
System.out.println(obj instanceof Test); // true
System.out.println(obj instanceof IObject); // true
}
}
結論:實例同時屬於其類、所有父類、實現的所有接口及 Object。可用於安全向下轉型前檢查。
String[] arr = new String[5];
System.out.println(arr instanceof String[]); // true
System.out.println(arr instanceof Object[]); // true(數組協變)
System.out.println(arr instanceof Cloneable); // true(數組實現 Cloneable/Serializable)
注意:基本類型數組(如 int[])僅是 Object、Cloneable、Serializable 的實例,不是 Object[] 的實例。
Object obj = "Hello";
if (obj instanceof String s) {
// s 直接可用,無需轉型
System.out.println(s.length());
}
編譯器自動完成「判斷+轉型+賦值」,減少樣板代碼,提升可讀性與作用域安全性。
"abc" instanceof Integer 編譯報錯(類型層級無關)。list instanceof List<String> 非法,只能寫 list instanceof List。instanceof 高度優化,通常不成為瓶頸;但熱點循環中大量使用仍建議優先多態設計。instanceof 核心價值在於運行時類型識別。掌握其在繼承鏈、接口、數組、泛型擦除、模式匹配中的行為細節,能寫出更安全、更現代的 Java 代碼。