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

记录模式的优势

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

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

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

相关推荐
oioihoii3 小时前
C++共享内存小白入门指南
java·c++·算法
@淡 定4 小时前
线程安全的日期格式化:避免 SimpleDateFormat 并发问题
java
qq_12498707534 小时前
基于springboot框架的小型饮料销售管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·spring·毕业设计
CodeAmaz4 小时前
JVM一次完整GC流程详解
java·jvm·gc流程
降临-max4 小时前
JavaWeb企业级开发---Ajax、
java·ajax·maven
NMBG224 小时前
外卖综合项目
java·前端·spring boot
小徐Chao努力4 小时前
Spring AI Alibaba A2A 使用指南
java·人工智能·spring boot·spring·spring cloud·agent·a2a
rannn_1114 小时前
【Git教程】概述、常用命令、Git-IDEA集成
java·git·后端·intellij-idea
我家领养了个白胖胖4 小时前
向量化和向量数据库redisstack使用
java·后端·ai编程
苹果醋35 小时前
Java设计模式实战:从面向对象原则到架构设计的最佳实践
java·运维·spring boot·mysql·nginx