记录类(Record)是Java 16正式引入的标准特性,旨在简化不可变数据载体的创建。其设计目标包括:
特性 | 普通类 | 记录类 |
---|---|---|
默认修饰符 | 无限制 | 隐式final |
继承 | 支持继承 | 不可继承其他类 |
可变性 | 可自由设计 | 隐式不可变 |
方法生成 | 手动实现 | 自动生成规范方法 |
构造器 | 显式定义 | 紧凑构造器 |
序列化 | 需显式实现 | 自动处理 |
public record User(
Long id,
String username,
String email,
LocalDateTime createTime
) implements Serializable {
// 可选的静态字段
private static final long serialVersionUID = 1L;
// 紧凑构造器(参数校验)
public User {
Objects.requireNonNull(id);
if (username.length() < 3) {
throw new IllegalArgumentException("用户名过短");
}
}
// 自定义方法
public String domain() {
return email.split("@")[1];
}
}
编译器会自动生成以下方法:
id()
而非getId()
)equals()
/hashCode()
toString()
等效普通类代码示例:
public final class User {
private final Long id;
private final String username;
// 其他字段...
public User(Long id, String username, ...) {
// 字段初始化...
}
// 自动生成的访问器和标准方法...
}
public record GeoPoint(double latitude, double longitude) {}
public record Address(
String street,
String city,
GeoPoint coordinates
) {
public Address {
if (!isValidCoordinate(coordinates)) {
throw new IllegalArgumentException("非法坐标");
}
}
private boolean isValidCoordinate(GeoPoint point) {
return Math.abs(point.latitude()) <= 90
&& Math.abs(point.longitude()) <= 180;
}
}
// JDK 17预览特性(模式匹配增强)
Object obj = new User(1L, "john", ...);
if (obj instanceof User(Long id, String name, var email, _)) {
System.out.println("用户ID:" + id + " 姓名:" + name);
}
public interface Timestamp {
default String formatTime() {
return createTime().format(DateTimeFormatter.ISO_LOCAL_DATE);
}
LocalDateTime createTime();
}
public record Product(
String sku,
String name,
LocalDateTime createTime
) implements Timestamp {}
反编译后的等效类结构:
public final class User extends Record {
private final Long id;
private final String username;
// 其他字段...
public User(Long id, String username, ...) {
// 参数校验逻辑...
this.id = id;
this.username = username;
// 其他字段初始化...
}
public Long id() { return this.id; }
public String username() { return this.username; }
// 自动生成的equals/hashCode/toString...
}
记录类的字段布局经过JVM特别优化:
// 使用数组记录提升性能(数值计算场景)
public record Vector(double[] components) {
public Vector {
components = Arrays.copyOf(components, components.length);
}
public double magnitude() {
return Math.sqrt(Arrays.stream(components)
.map(v -> v*v)
.sum());
}
}
public record Company(String name, List<String> departments) {
// 防御性拷贝
public Company {
departments = List.copyOf(departments);
}
public List<String> departments() {
return Collections.unmodifiableList(departments);
}
}
记录类自动支持序列化:
// 序列化
User user = new User(1L, "john", ...);
try (ObjectOutputStream oos = new ObjectOutputStream(...)) {
oos.writeObject(user);
}
// 反序列化保证
User deserialized = (User) ois.readObject();
System.out.println(user.equals(deserialized)); // true
通过接口扩展功能:
public interface Auditable {
default String auditInfo() {
return "Created at: " + LocalDateTime.now();
}
}
public record Order(String id, BigDecimal amount) implements Auditable {}
Java记录类重新定义了数据建模的方式,通过语法糖与JVM级优化的结合,实现了简洁性、安全性和性能的完美平衡。作为现代Java开发的重要特性,它不仅大幅减少了模板代码,更为模式匹配、值类型等未来特性奠定了基础。在微服务、函数式编程等场景下,合理运用记录类将显著提升代码质量和开发效率。随着Java语言的持续演进,记录类将在数据驱动开发中发挥更加关键的作用。