JDK 21新特性---记录模式匹配

记录模式匹配

Record Classes

  • 在JDK 16中加入了Record Class,它自动生成了构造函数、访问器、equals、hashCode、toString等方法,简化代码的编写,类似于lombok插件的@Data注解。

  • 类简化对比:

      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 void setName(String name) {
              this.name = name;
          }
    
          public Integer getType() {
              return type;
          }
    
          public void setType(Integer type) {
              this.type = type;
          }
      }
    
      //Record类
      public record MyRecord(String name, Integer type) {
      }
    

Record Pattern

  • 记录模式匹配是指自动匹配Record Classes,从而简化代码

  • 实例对比:

      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);
              }
          }
      }
    
posted on 2023-10-10 10:46  大胖头  阅读(68)  评论(0编辑  收藏  举报