03- javaBean 新花样? record 新特性

定义和特性

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

  1. 不可变的字段
  2. 一个规范的构造器
  3. 每个元素(组件)都有访问方法
  4. equals
  5. hashCode
  6. toString
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 ,进行转化, 等价处理。

//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现在做为数据传输类更多的是支持函数式编程,也是这样来避免并发会出现的问题。
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值