随笔 - 15  文章 - 4  评论 - 4  阅读 - 6733

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   大胖头  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示