Java 21记录模式与模式匹配深度解析

Java 21引入的记录模式(Record Patterns)为数据导向编程提供了革命性工具,允许开发者以声明式的方式解构和处理数据对象。这一特性显著简化了类型判断和结构解构的过程。

核心特性详解

基础记录类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public record Person(String name, int age, String email) {
    // 自动生成构造函数、访问器和方法
}

public record Address(String street, String city, String zipCode) {
    // 验证逻辑
    public Address {
        Objects.requireNonNull(street, "Street cannot be null");
    }
}

记录模式解构

1
2
3
4
5
public void processPerson(Object obj) {
    if (obj instanceof Person(String name, int age, String email)) {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

高级应用场景

嵌套记录模式

处理复杂的嵌套记录结构:

1
2
3
4
5
6
7
8
public record Employee(Person person, Department department) {}

public String getEmployeeInfo(Employee emp) {
    return switch (emp) {
        case Employee(Person(String name, int age, _), Department(String deptName)) 
            -> name + " works in " + deptName;
    };
}

Switch表达式集成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public String formatEvent(DomainEvent event) {
    return switch (event) {
        case UserCreatedEvent(var userId, var username) 
            -> "User created: " + username + " (ID: " + userId + ")";
        case UserUpdatedEvent(var userId, var changes) 
            -> "User updated: " + userId + " with changes: " + changes;
        case UserDeletedEvent(var userId, String reason) 
            -> "User deleted: " + userId + ", reason: " + reason;
    };
}

实际应用案例

API响应处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public sealed interface ApiResponse<T> permits Success, Error {
    record Success<T>(T data, Pagination pagination) implements ApiResponse<T> {}
    record Error<T>(String code, String message) implements ApiResponse<T> {}
}

public <T> void handleResponse(ApiResponse<T> response) {
    switch (response) {
        case ApiResponse.Success<T>(var data, var pagination) ->
            processData(data, pagination);
        case ApiResponse.Error<T>(var code, var message) ->
            handleError(code, message);
    }
}

配置解析优化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public record DatabaseConfig(String url, String username, String password) {}
public record ServerConfig(String host, int port, boolean ssl) {}
public record AppConfig(DatabaseConfig db, ServerConfig server) {}

public void setupApplication(AppConfig config) {
    if (config instanceof AppConfig(
        DatabaseConfig(String url, String user, String pass),
        ServerConfig(String host, int port, boolean ssl)
    )) {
        // 配置初始化逻辑
    }
}
本博客已稳定运行
共14篇文章 · 共8.03k字
使用 Hugo 构建
主题 StackJimmy 设计 由 iTang 优化