boolean result = object instanceof Type;
// 等價於:object != null && object.getClass() 是 Type 或其子類/實現類
boolean,從不拋異常null instanceof Type 永遠返回 falseobject 靜態類型與 Type 無繼承關係,直接編譯錯誤interface Animal {}
class Dog implements Animal {}
class Cat implements Animal {}
Animal a = new Dog();
Dog d = new Dog();
a instanceof Animal // true
a instanceof Dog // true(運行時類型是 Dog)
a instanceof Cat // false
d instanceof Animal // true
d instanceof Dog // true
d instanceof Cat // false(編譯期允許,運行時 false)
Object obj = getObject();
if (obj instanceof String) {
String s = (String) obj; // 需顯式強轉
System.out.println(s.toUpperCase());
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
System.out.println(i * 2);
}
Object obj = getObject();
if (obj instanceof String s) { // 直接宣告模式變數
System.out.println(s.toUpperCase()); // s 僅在 true 分支作用域有效
} else if (obj instanceof Integer i) {
System.out.println(i * 2);
}
// 作用域規則:模式變數僅在 instanceof 為 true 時確定賦值
// 以下編譯錯誤:
// if (obj instanceof String s) { }
// s.toUpperCase(); // s 不在作用域
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double a, double b, double c) implements Shape {}
public double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.w() * r.h();
case Triangle t -> {
double s = (t.a() + t.b() + t.c()) / 2;
yield Math.sqrt(s * (s - t.a()) * (s - t.b()) * (s - t.c()));
}
// 密封類保證窮盡,無需 default
};
}
List
instanceof 極快(JVM 內建指令),納秒級| 誤區 | 正確認知 |
|---|---|
| instanceof 檢查具體類而非介面 | 可檢查類、介面、陣列類型、record、enum |
| null 會拋 NPE | null instanceof X 直接返回 false,安全 |
| 模式變數可在外部使用 | 作用域僅限於 true 分支(flow scoping) |
| 可用於基本型別 | 僅限引用類型,int/boolean 等不可用 |
| 泛型類型可完整檢查 | 運行時類型擦除,List |
instanceof Type varinstanceof 從簡單的類型檢查進化為強大的模式匹配工具。配合 sealed、record、switch 表達式,Java 實現了接近函數式語言的代數資料類型解構能力。現代 Java 開發者應熟練掌握 instanceof Type var 語法,並在領域建模中善用密封類層次結構,讓編譯器幫你檢查邏輯完整性。