Java Record
public class Test {
record Person(String firstName, String lastName, int age) {
}
public static void main(String[] args) {
var me = new Person("Riguz", "Lee", 20);
System.out.println(me);
}
}
Output:
Person[firstName=Riguz, lastName=Lee, age=20]
- Record是不可变对象
- 自动实现了构造方法,equlas,hashcode,toString
- 可以实现接口、添加方法
- 可以添加构造器的检测:
public class Test {
record Person(String firstName, String lastName, int age) {
public Person {
if(age < 0 || age > 100)
throw new IllegalArgumentException("Age is invalid");
}
}
}