【java21】java21新特性之记录模式

Java21引入的新特性------记录模式(Record Patterns),是对Java语言模式匹配功能的进一步扩展。

记录模式的定义与目的

记录模式是Java语言中的一个新特性,旨在简化和标准化对记录类实例的解构,允许程序员更加方便、安全地访问和操作记录类的组件。记录类本身是在Java 14中引入的,作为一种简化不可变数据类定义的方式。记录模式通过编译时检查确保访问的正确性,避免错误的字段访问或类型不匹配问题,并使代码更加简洁明了。

记录模式在if中的使用

java 复制代码
public static void testInIf(Object object) {
    if (object instanceof Points points) {
        System.out.println("pre jdk 19 object is a position, x = " + points.x()
                + ", y = " + points.y());
    }
    if (object instanceof Points(int x, int y)) {
        System.out.println("jdk 19 object is a position, x = " + x + ", y = " + y);
    }
}

记录模式在switch中的使用

java 复制代码
public static void testInSwitch(Object object) {
    switch (object) {
        case Points points -> System.out.println("pre jdk 19 object is a position, x = " + points.x() + ", y = " + points.y());
            default -> throw new IllegalStateException("Unexpected value: " + object);
    }
    switch (object) {
        case Points(int x, int y) -> System.out.println("jdk 19 object is a position, x = " + x + ", y = " + y);
            default -> throw new IllegalStateException("Unexpected value: " + object);
    }
}

记录模式的嵌套使用

java 复制代码
public static void testInNest(Object object) {
    if (object instanceof Line(Points(int x1, int y1), Points(int x2, int y2))){
        System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1 + ", x2 = " + x2 + ", y2 = " + y2);
    }
    switch (object) {
        case Line(Points(int x1, int y1), Points(int x2, int y2)) ->
            System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1 + ", x2 = " + x2 + ", y2 = " + y2);
            // other cases ...
            default -> throw new IllegalStateException("Unexpected value: " + object);
    }
}

记录模式的优势

清晰性:记录模式使代码更加简洁明了,减少了访问记录类字段的样板代码。

安全性:通过编译时检查确保访问的正确性,避免错误的字段访问或类型不匹配问题。

效率:编译器可以生成更高效的代码,因为模式匹配的意图明确,减少了运行时的开销。

相关推荐
Y***h1872 小时前
第二章 Spring中的Bean
java·后端·spring
8***29312 小时前
解决 Tomcat 跨域问题 - Tomcat 配置静态文件和 Java Web 服务(Spring MVC Springboot)同时允许跨域
java·前端·spring
CoderYanger2 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
q***06292 小时前
Tomcat的升级
java·tomcat
多多*2 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
青云交2 小时前
Java 大视界 -- Java 大数据在智能物流无人配送车路径规划与协同调度中的应用
java·spark·路径规划·大数据分析·智能物流·无人配送车·协同调度
d***81723 小时前
解决SpringBoot项目启动错误:找不到或无法加载主类
java·spring boot·后端
ᐇ9593 小时前
Java集合框架深度实战:构建智能教育管理与娱乐系统
java·开发语言·娱乐
听风吟丶4 小时前
MyBatis 深度实战:从基础映射到企业级性能优化
java·tomcat
仟濹4 小时前
【Java 基础】面向对象 - 继承
java·开发语言