【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);
    }
}

记录模式的优势

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

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

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

相关推荐
wuminyu1 小时前
C++协程实现接收端的零拷贝Buffer管理原理剖析
java·linux·c语言·jvm·c++
蜗牛互联网3 小时前
WSL Containers GA:本地AI容器的生命周期、网络与治理验收
java·网络·人工智能·后端
龙亘川4 小时前
铭记英烈守初心,数字强基促服务:亘川智城退役军人服务系统的实践与价值
java·数据库·人工智能
OxYGC4 小时前
[AI工程] Spring AI 第廿一篇:存量 REST 接口的 MCP 化改造实录——工具从哪条路径注册、参数描述怎么写、身份怎么过去
java·人工智能·spring
Zhou1411365 小时前
SpringBoot_02_自动配置原理
java·spring boot·后端
FYKJ_20105 小时前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv1105 小时前
Android studio国内开发有关
java·数据库·android studio
卓怡学长5 小时前
w198基于springboot始于足下健康打卡平台的设计与实现
java·spring boot·spring·intellij-idea
阿狗童鞋5 小时前
Java并发编程实战指南
java·开发语言
Joe_Wang56 小时前
【从0到1学习JVM · 15】对象在堆里来回倒腾,究竟怎样才会进老年代?
java·jvm·学习·垃圾回收