java中record,Java 中的 record 关键字

在 Java 中,record 关键字用于声明充当“数据载体”的特殊类类型,即领域模型类或 POJO 类。从 JDK 14 起,此关键字已添加到 Java 语言中。

例如:

record Point(int x, int y) { }

Java 编译器将为 record 类型生成 equals(),hashCode(),toString() 方法,以及生成适当的构造函数,并且为所有字段生成 getter 和 setter 。 上面的 record 类型 Point 等效于以下 class 代码:

public class Point {

private int x;

private int y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

public void setX(int x) {

this.x = x;

}

public int getX() {

return this.x;

}

public void setY(int y) {

this.y = y;

}

public int getY() {

return this.y;

}

public boolean equals(Object obj) {

// implement equals based on fields x and y

}

public int hashCode() {

// implement hashCode based on fields x and y

}

public String toString() {

// implement toString based on fields x and y

}

}

使用 record 类型,可以在编写 POJO 类时节省大量时间。

record 类型功能在 JDK 14(预览版)中进行审查,并将在之后的 JDK 版本中完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值