从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){ 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
关键字也可以达到同样的效果,但是代码量相对较大