Java 21 新特性:记录类与模式匹配

1. 记录类(Record Classes)

记录类是轻量级的不可变数据载体,可自动生成构造方法、访问器、equals()hashCode()toString() 方法。
语法示例

record Point(int x, int y) {}  // 定义记录类

特点

  • 不可变性:所有字段隐式为 final
  • 简洁性:无需手动编写样板代码。
  • 模式匹配支持:可直接用于模式解构。

使用场景

Point p = new Point(3, 4);
System.out.println(p.x());  // 输出: 3 (自动生成访问器)


2. 模式匹配(Pattern Matching)

模式匹配简化了对象类型检查和提取操作,与 instanceofswitch 深度集成。

(1) instanceof 模式匹配

传统方式

if (obj instanceof String) {
    String s = (String) obj;  // 需显式强制转换
    System.out.println(s.length());
}

Java 21 改进

if (obj instanceof String s) {  // 直接绑定变量
    System.out.println(s.length());  // 无需强制转换
}

(2) switch 模式匹配

结合记录类的解构

record Circle(double radius) {}
record Rectangle(double w, double h) {}

// 模式匹配解构
static double area(Shape shape) {
    return switch (shape) {
        case Circle c    -> Math.PI * c.radius() * c.radius();
        case Rectangle r -> r.w() * r.h();  // 直接访问字段
        default          -> 0.0;
    };
}


3. 记录类与模式匹配的协同优势

示例:几何计算

sealed interface Shape permits Circle, Rectangle {}  // 密封接口
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle(5.0);
        System.out.println(describe(circle));  // 输出: 圆形(半径=5.0)
    }

    static String describe(Shape shape) {
        return switch (shape) {
            case Circle c      -> String.format("圆形(半径=%.1f)", c.radius());
            case Rectangle r   -> String.format("矩形(宽=%.1f, 高=%.1f)", r.w(), r.h());
        };
    }
}

优势

  • 类型安全:密封接口确保所有子类已知。
  • 解构简化:直接提取记录类字段。
  • 可读性提升:避免冗余的类型检查和转换。

4. 应用场景
  • 数据传输对象(DTO):替代 Lombok 的 @Data 注解。
  • 状态处理:如解析 JSON 或 XML 数据时快速提取字段。
  • 函数式编程:结合 Stream API 实现声明式数据处理。
5. 升级建议
  • 在需要不可变数据的场景优先使用记录类。
  • 逐步替换旧版 instanceofswitch 代码,提升健壮性。
  • 结合密封类(sealed)确保模式匹配覆盖所有类型。

通过记录类和模式匹配,Java 显著减少了样板代码,提升了类型安全性和代码表达力,是现代化 Java 开发的核心特性。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐