问题描述
我有很多使用Lombok的“数据”类,我想迁移所有这些类以使用Java 14中可用的新Record功能。借助新的Java 14 Record功能,是否可以为相同的记录?如果没有,还有其他选择吗?
解决方法
从Java 15开始(请参见JEP 384: Records (Second Preview)),您可能在记录中有多个构造函数。
但是,每个构造函数必须委托给记录的规范构造函数,该构造函数可以明确定义或自动生成。
一个例子:
public record Person(
String firstName,String lastName
) {
// Compact canonical constructor:
public Person {
// Validations only; fields are assigned automatically.
Objects.requireNonNull(firstName);
Objects.requireNonNull(lastName);
// An explicit fields assignment,like
// this.firstName = firstName;
// would be a syntax error in compact-form canonical constructor
}
public Person(String lastName) {
// Additional constructors MUST delegate to the canonical constructor,// either directly:
this("John",lastName);
}
public Person() {
// ... or indirectly:
this("Doe");
}
}
另一个例子:
public record Person(
String firstName,String lastName
) {
// Canonical constructor isn't defined in code,// so it is generated implicitly by the compiler.
public Person(String lastName) {
// Additional constructors still MUST delegate to the canonical constructor!
// This works:
this("John",lastName);
// (Re-)Assigning fields here directly would be a compiler error:
// this.lastName = lastName; // ERROR: Variable 'lastName' might already have been assigned to
}
public Person() {
// Delegates to Person(String),which in turn delegates to the canonical constructor:
this("Doe");
}
}