boolean result = obj instanceof Type;
// obj 為 null 時直接返回 false,不拋 NPE
// obj 為 Type 或其子類實例返回 true
核心規則:編譯期類型必須與目標類型有繼承關係(父子、實現、同類),否則編譯錯誤「Incompatible types」。
// 傳統寫法:兩次類型檢查
if (obj instanceof String) {
String s = (String) obj; // 強制轉換
System.out.println(s.length());
}
// JDK 14+ 模式匹配預覽 / JDK 16+ 正式:一步到位
if (obj instanceof String s) {
// s 為模式變量,作用域限於 if 塊內
System.out.println(s.length());
}
// 複雜條件結合
if (obj instanceof List> list && !list.isEmpty()) {
System.out.println("First: " + list.get(0));
}
interface Animal {}
class Dog implements Animal {}
class Cat implements Animal {}
class Husky extends Dog {}
public class InstanceofDemo {
public static void main(String[] args) {
Animal a = new Husky();
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Husky); // true
System.out.println(a instanceof Cat); // false
System.out.println(a instanceof String); // 編譯錯誤:無關類型
// null 情況
Animal nullRef = null;
System.out.println(nullRef instanceof Dog); // false
}
}
List
// 密封類限制實現類
sealed interface Expr permits Const, Plus, Mult {}
record Const(int value) implements Expr {}
record Plus(Expr left, Expr right) implements Expr {}
record Mult(Expr left, Expr right) implements Expr {}
int eval(Expr expr) {
return switch (expr) {
case Const(int v) -> v;
case Plus(Expr l, Expr r) -> eval(l) + eval(r);
case Mult(Expr l, Expr r) -> eval(l) * eval(r);
// 編譯器檢查窮盡性,無需 default
};
}
優勢:類型安全、編譯期窮盡性檢查、語法簡潔、無需 Visitor 接口樣板代碼。
obj instanceof List ❌ 編譯錯誤,只能 instanceof List> 或 instanceof Listobj instanceof int[] ✅,obj instanceof List[] ✅| 特性 | instanceof | getClass() == |
|---|---|---|
| 子類實例 | true | false |
| null 處理 | false | 拋 NPE |
| 語義 | 是否為類型族成員 | 是否為精確類型 |
| 推薦場景 | 多態類型判斷 | 精確類型校驗(如序列化、複製) |