Record Patterns
JDK 21 正式引入了 Record Patterns,允许对 Record 类型进行解构和模式匹配。
基本语法
java
// 传统方式
if (obj instanceof Point) {
Point p = (Point) obj;
System.out.println(p.x() + p.y());
}
// Record Pattern
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y);
}switch 中的 Record Pattern
java
String describe(Object obj) {
return switch (obj) {
case Point(int x, int y) when x == y -> "对角线点";
case Point(int x, int y) -> "普通点";
case null -> "null";
default -> "其他";
};
}小结
Record Patterns 简化了 Record 类型的处理:
- 解构赋值
- switch 中的模式匹配
- 带条件的模式匹配(when)
JDK 21+ 可用。
