Java record关键字

从Java14开始,引入了新的关键字record,该关键字的能让我们快速地编写一些数据类(Data Class):

基本语法

1
public record User(String username, String password){}

上述代码等同于:

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
final class User extends Record{
private final String username;
private final String password;

public User(String username, String password){
this.username = username;
this.password = password;
}

public String username(){
return this.username;
}

public String password(){
return this.password;
}

public String toString(){
return String.format("User[username=%s, password=%s]", this.username, this.password);
}

public boolean equals(Object o){
//...
}

public int hashCode(){
//..
}
}

record关键字相当于创建了一个final类,并且其中的字段也都是final的,还会自动生成与字段同名的getter方法、toString方法、equals方法、hashCode方法以及一个构造函数。

Record类禁止被继承,所以只能让Java虚拟机去创建Record子类,形如A extends Record的代码是无法通过编译的。

Compact Constructor

如果我们需要对传入类的参数进行校验,就可以使用Compact Constructor,以上述User类为例:

1
2
3
4
5
6
7
public record User(String username, String password){
public User{
if(username.isEmpty() || password.isEmpty()){
throw new IllegalArgumentException();
}
}
}

Compact Constructor的定义没有小括号,可以直接使用成员属性。实际上,我们所编写的Compact Constructor会被添加到Java自动生成的构造函数的开头:

1
2
3
4
5
6
7
8
9
10
11
// 上述代码相当于
public User(String username, String password){
public User(String username, String password){
// 刚才编写的Compact Constructor的内容
if(username.isEmpty() || password.isEmpty()){
throw new IllegalArgumentException();
}
this.username = username;
this.password = password;
}
}

静态方法

可以在record类中编写一些静态方法,一般来说是名为of的方法,给外部调用来创建该类的实例。

1
2
3
4
5
6
7
8
public record User(String username, String password){
public static User of(){
return new User("user", "123");
}
public static User of(String username, String password){
return new User(username, password);
}
}

record关键字的存在完全是为了简化代码的编写,不使用record关键字也可以达到同样的效果,但是代码量相对较大