java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java record

Java中的record使用详解

作者:芦屋花绘

record 是 Java 14 引入的一种新语法(在 Java 16 中成为正式功能),用于定义不可变的数据类,这篇文章给大家介绍Java中的record相关知识,感兴趣的朋友一起看看吧

1. 什么是 record?

定义record 是 Java 14 引入的一种新语法(在 Java 16 中成为正式功能),用于定义不可变的数据类。

2. 基本语法

public record ClassName(Type fieldName1, Type fieldName2, ...) {
    // 可选:可以添加额外的方法或逻辑
}

示例

public record Point(int x, int y) {
}

等价于以下传统类定义:

public final class Point {
    private final int x;
    private final int y;
    // 全参构造器
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    // Getter 方法
    public int x() { return x; }
    public int y() { return y; }
    // 自动覆盖 equals 和 hashCode
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Point)) return false;
        Point other = (Point) obj;
        return this.x == other.x && this.y == other.y;
    }
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
    // 自动覆盖 toString
    @Override
    public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}

3. record 的核心特性

(1)字段不可变

public record Point(int x, int y) {}
Point p = new Point(1, 2);
// p.x = 3; // 编译错误:x 是 final 的,不能修改

(2)自动生成方法

示例

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
System.out.println(p1.equals(p2)); // 输出 true
System.out.println(p1.hashCode()); // 输出基于字段值的哈希码
System.out.println(p1);           // 输出 Point[x=1, y=2]

(3)简洁性

4. 使用场景

(1)封装简单数据结构

public record User(String name, int age) {}
User user = new User("Alice", 25);
System.out.println(user.name()); // 输出 Alice

(2)配置类

@ConfigurationProperties(prefix = "app")
public record AppProperties(String name, int port) {}

(3)DTO(数据传输对象)

public record BookDto(String title, String author, double price) {}

5. 自定义行为

虽然 record 自动生成了许多方法,但你仍然可以对其进行扩展。

(1)添加额外方法

可以在 record 中定义额外的方法。

public record Point(int x, int y) {
    public double distanceFromOrigin() {
        return Math.sqrt(x * x + y * y);
    }
}
Point p = new Point(3, 4);
System.out.println(p.distanceFromOrigin()); // 输出 5.0

(2)自定义构造函数

你可以通过紧凑构造函数对字段进行验证或其他操作。

public record Point(int x, int y) {
    public Point {
        if (x < 0 || y < 0) {
            throw new IllegalArgumentException("Coordinates cannot be negative");
        }
    }
}
// Point p = new Point(-1, 2); // 抛出异常

紧凑构造函数 是 record 提供的一种简洁语法,用于在不手动写构造参数和赋值的前提下,插入自定义逻辑(如校验),简洁高效,专为不可变数据对象设计。

6. 注意事项

(1)字段不可变

(2)继承限制

public final class Point extends java.lang.Record {
    private final int x;
    private final int y;
    // 自动生成构造方法、getters、toString、equals、hashCode 等
}

record 可以实现接口。

public record Point(int x, int y) implements Serializable {}

(3)不适合复杂逻辑

record 主要用于简单的数据载体,不适合包含复杂的业务逻辑。

(4)兼容性

7. 总结

优点

适用场景

限制

到此这篇关于Java中的record详解的文章就介绍到这了,更多相关Java record内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文