Java 模式匹配:类型检查与解构
学习 instanceof 和 switch 中的模式匹配,简化类型检查和对象解构,写出更安全的代码。 · 难度:入门 · +15XP
传统 instanceof 的问题
if (obj instanceof String) {
String s = (String) obj; // 手动强制转换
System.out.println(s.length());
}需要先检查类型再强转,代码冗余且容易出错。
模式匹配 instanceof(Java 16+)
if (obj instanceof String s) {
System.out.println(s.length()); // 直接使用 s
}变量 s 的作用域限定在 if 块内,且仅在类型匹配时可用。
Switch 中的模式匹配(Java 17+ 预览)
String formatted = switch (obj) {
case Integer i -> String.format("int %d", i);
case String s -> String.format("String %s", s);
case null -> "null";
default -> "unknown";
};注意:null 也可以作为独立 case,避免空指针。
记录模式(Java 19+ 预览)
record Point(int x, int y) {}
if (obj instanceof Point(int x, int y)) {
System.out.println("x=" + x + ", y=" + y);
}
可以直接解构 record 的组件。
练习提示
在 starter_code 中,使用模式匹配 instanceof 判断对象类型并打印对应信息。