03、Java 21 新特性 - 记录模式

使用记录模式(Record Patterns)增强Java编程语言,以解构记录值。可以嵌套记录模式和类型模式,以实现功能强大、声明性和可组合形式的数据导航和处理。

Record Patterns

该功能首次在 Java SE 19 中预览,在Java SE 20中发布第二次预览版,在此版本中成为永久性功能。这意味着它可以在任何为 Java SE 21 编译的程序中使用,而无需启用预览功能。

示例代码如下

package git.snippets.jdk21;

/**
 * record 模式匹配增强
 * 无须增加 --enable-preview参数

 * @since 21
 */
public class RecordTest {
   
     
    public static void main(String[] args) {
   
     
        Points points = new Points(1, 2);
        Line line = new Line(new Points(1, 2), new Points(3, 4));
        printPoints(points);
        printLine(line);
    }
    private static void printPoints(Object object) {
   
     
        if (object instanceof Points(int x, int y)) {
   
     
            System.out.println("jdk 19 object is a position, x = " + x + ", y = " + y);
        }
        if (object instanceof Points points) {
   
     
            System.out.println("pre jdk 19 object is a position, x = " + points.x()
                    + ", y = " + points.y());
        }
        switch (object) {
   
     
            case Points position -> System.out.println("pre jdk 19 object is a position, x = " + position.x()
                    + ", y = " + position.y());
            default -> throw new IllegalStateException("Unexpected value: " + object);
        }
        switch (object) {
   
     
            case Points(int x, int y) -> System.out.println(" jdk 19 object is a position, x = " + x
                    + ", y = " + y);
            default -> throw new IllegalStateException("Unexpected value: " + object);
        }

    }

    public static void printLine(Object object) {
   
     
        if (object instanceof Line(Points(int x1, int y1), Points(int x2, int y2))) {
   
     
            System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
                    + ", x2 = " + x2 + ", y2 = " + y2);
        }
        switch (object) {
   
     
            case Line(Points(int x1, int y1), Points(int x2, int y2)) ->
                    System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
                            + ", x2 = " + x2 + ", y2 = " + y2);
            // other cases ...
            default -> throw new IllegalStateException("Unexpected value: " + object);
        }
    }

}

record Points(int x, int y) {
   
     
}

record Line(Points from, Points to) {
   
     
}