Java记录类深度解析:不可变数据建模的现代实践
一、技术优势
记录类使样板代码减少75%,同时提供更强的类型安全性
// 传统Java类 vs 记录类
class Point { | record Point(
final int x; | int x,
final int y; | int y
// 构造/equals/hashCode等 | ) {}
} |
二、核心语法
1. 基础记录定义
public record User(
Long id,
String username,
@Size(max=100) String email
) {
// 紧凑构造器
public User {
Objects.requireNonNull(username);
}
}
2. 高级模式匹配
record Circle(Point center, int radius) {}
record Rectangle(Point topLeft, int width, int height) {}
double area(Shape shape) {
return switch (shape) {
case Circle(Point p, int r) -> Math.PI * r * r;
case Rectangle(_, int w, int h) -> w * h;
};
}
三、高级应用
1. 构建器模式实现
record Person(String name, int age, String address) {
static class Builder {
private String name;
private int age;
private String address;
Builder name(String name) { this.name = name; return this; }
// 其他setter...
Person build() {
return new Person(name, age, address);
}
}
}
// 使用方式
Person p = new Person.Builder()
.name("张三")
.age(30)
.build();
2. JSON序列化优化
record ApiResponse<T>(
int code,
String message,
T data
) {}
// 自动生成JSON结构
{
"code": 200,
"message": "success",
"data": {...}
}
四、完整案例
电商领域模型
public record Product(
String sku,
String name,
Money price,
List<Category> categories
) implements Serializable {
public Product {
categories = List.copyOf(categories); // 防御性拷贝
}
}
public record Order(
String orderId,
Customer customer,
List<OrderItem> items,
OrderStatus status
) {
public BigDecimal total() {
return items.stream()
.map(OrderItem::subtotal)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
public record OrderItem(
Product product,
int quantity
) {
public BigDecimal subtotal() {
return product.price().multiply(
BigDecimal.valueOf(quantity));
}
}
function checkJavaVersion() {
alert(‘请使用Java16+运行示例代码,记录类是正式特性’);
}