03- javaBean 新花样? record 新特性

定义和特性

JDK16 最终增加了record关键字,record定义的类希望成为数据传输对象 也叫数据载体,使用record 时候,编译器会自动生成:

  1. 不可变的字段
  2. 一个规范的构造器
  3. 每个元素(组件)都有访问方法
  4. equals
  5. hashCode
  6. toString
java 复制代码
public record Student(String name, int age) {  
  
	 // 简约 构造方法,不在这里写入参数 自动配置参数类型
    public Student {  
        //可以在这个地方进行校验参数
        if (Objects.isNull(name)) {  
            throw new RuntimeException("name is null");  
        }  
  
    }  


}


public class RecordTest {  
  
    public static void main(String[] args) {  
  
        Student student = new Student("小白", 20);  
        System.out.println(student.name());  
        System.out.println(student.age());  
        System.out.println(student.toString());  
  
    }  
}

---
小白
20
Student[name=小白, age=20]

编译器做了哪些事情呢? 可以通过 idea,里面的功能进行covert record to class ,进行转化, 等价处理。

java 复制代码
//final 修饰不会被继承
public final class Student {  
    private final String name;  
    private final int age;  
  
    public Student(String name, int age) {  
        this.name = name;  
        this.age = age;  
    }  
  
    @Override  
    public String toString() {  
        return "Student[" +  
                "name=" + name + ", " +  
                "age=" + age + ']';  
    }  


	//只有访问方法,在没有set方法
    public String name() {  
        return name;  
    }  
  
    public int age() {  
        return age;  
    }  
  
    @Override  
    public boolean equals(Object obj) {  
        if (obj == this) return true;  
        if (obj == null || obj.getClass() != this.getClass()) return false;  
        var that = (Student) obj;  
        return Objects.equals(this.name, that.name) &&  
                this.age == that.age;  
    }  
  
    @Override  
    public int hashCode() {  
        return Objects.hash(name, age);  
    }  
  
}

注意事项

  1. record 里面字段就是组件的不可变是引用不可变,如果是对象的话,里面的参数是可变的
  2. record现在做为数据传输类更多的是支持函数式编程,也是这样来避免并发会出现的问题。
相关推荐
葵续浅笑2 分钟前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
装不满的克莱因瓶12 分钟前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud
杨筱毅18 分钟前
【穿越Effective C++】条款13:以对象管理资源——RAII原则的基石
开发语言·c++·effective c++
N 年 后24 分钟前
cursor和传统idea的区别是什么?
java·人工智能·intellij-idea
CodeLongBear41 分钟前
从Java后端到Python大模型:我的学习转型与规划
java·python·学习
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 94: 最长的斐波那契子序列的长度
java·数据结构·算法·leetcode·深度优先·动态规划
Zz_waiting.1 小时前
统一服务入口-Gateway
java·开发语言·gateway
ada7_1 小时前
LeetCode(python)——49.字母异位词分组
java·python·leetcode
DyLatte1 小时前
AI时代的工作和成长
java·后端·程序员
四维碎片1 小时前
【Qt】大数据量表格刷新优化--只刷新可见区域
开发语言·qt