Java21新特性 – 记录模式(JEP 440)

后端 潘老师 6个月前 (11-02) 369 ℃ (0) 扫码查看

1.前言

在讲Java21新特性 – 记录模式之前我们有必要回顾下JDK16中新增的Record记录。Record记录会自动生成了构造函数、getter、equals、hashCode、toString等方法,简化代码的编写,类似于lombok插件的@Data注解,但是对象属性只读,只有get方法,没有set方法。

我们通过一个简单的案例对比下使用Record和不使用record的区别:

// 使用class,不使用record
 public class MyRecord {
      private String name;
      private Integer type;

      public MyRecord(String name, Integer type) {
          this.name = name;
          this.type = type;
      }

      public String getName() {
          return name;
      }

      public Integer getType() {
          return type;
      }
  }

  //使用record,很简洁
  public record MyRecord(String name, Integer type) {
  }

通过上述案例想必大家对record记录已经有所了解,这一点在JDK17新特性汇总也有所提到,接下来我们一起看下记录模式。

2.什么是记录模式?

记录模式,也就是记录模式匹配,英文为“Record Patterns”,记录模式匹配是指自动匹配Record记录类,从而简化代码。

3.记录模式有什么作用?

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

4.记录模式如何使用?

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

我们来看下两个示例:

1)使用记录模式与未使用记录模式代码对比:

public record MyRecord(String name,Integer type) {
  
      //未使用记录模式匹配的代码
      static void print(Object data){
          if(data instanceof MyRecord){
              // 这里还需要强转
              MyRecord myRecord=(MyRecord)data;
              System.out.println("name:"+myRecord.name()+",type:"+myRecord.type());
          }
      }
  }
  
  public record MyRecord(String name,Integer type) {
      //使用了记录模式匹配的代码,简洁了很多
      static void print(Object data){
          if(data instanceof MyRecord(String name,Integer type)){
              System.out.println("name:"+name+",type:"+type);
          }
      }
  }

2)使用记录模式的其他示例,比如在instanceof和switch-case中匹配

/**
 * 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是一个坐标, x = " + x + ", y = " + y);
        }
        if (object instanceof Points points) {
            System.out.println("jdk 19之前 object是一个坐标, x = " + points.x()
                    + ", y = " + points.y());
        }
        switch (object) {
   
            case Points position -> System.out.println(" jdk 19之前 object是一个坐标, 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是一个坐标, 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是一个路径, 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是一个路径, x1 = " + x1 + ", y1 = " + y1
                            + ", x2 = " + x2 + ", y2 = " + y2);
            // 其他情况 ...
            default -> throw new IllegalStateException("Unexpected value: " + object);
        }
    }

}
// 坐标记录
record Points(int x, int y) {
     
}
// 路径记录
record Line(Points from, Points to) {
     
}

5.总结

以上就Java21新特性 – 记录模式的内容详解。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/10568.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】