在 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 版本中完成。