java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java record使用

Java Record的使用场景分析

作者:麻辣香蝈蝈

Java的Record用于简化不可变数据类定义,自动提供构造器、equals、hashCode等方法,字段默认final且不可变,适用于仅存储数据的场景,不支持手动添加非final字段,但允许扩展方法和静态成员,本文给大家介绍Java Record的使用,感兴趣的朋友一起看看吧

一、前言

二、学习内容:

三、问题描述

四、解决方案:

4.1 为什么引入Record

Java 引入 record 的主要原因是为了简化创建不可变数据类的过程,并提高代码的可读性和维护性。

以下是一些具体的原因:

减少样板代码:

不可变性:

简洁性:

性能优化:

模式匹配的支持:

易于调试:

明确的意图:

4.2 Record与Class区别

package org.example.recodes;
import java.util.Objects;
public class Cat {
    String name;
    public String getName() {
        return name;
    }
    public Cat(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Cat cat = (Cat) o;
        return Objects.equals(name, cat.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}
package org.example.recodes;
public record RecordCat(String name) { }

🌟 上面两段代码是等效的

record 自动生成构造器、equals()、hashCode() 和 toString() 方法,以及每个字段的 getter方法

我们运行一下下面代码看看区别

package org.example.recodes;
public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat("mimi");
        System.out.println(cat.getName());
        System.out.println(cat);
        RecordCat recordCat = new RecordCat("momo");
        System.out.println(recordCat.name());
        System.out.println(recordCat);
    }
}

结果如下:

4.3 语法与使用场景

适用于那些仅用于存储数据而没有复杂业务逻辑的情况
结构体里面可扩展内容如下

⭐️Record所有字段默认是final

// 构造传入
public record Person(String name, int age) {  
    // 这是合法的,因为字段在声明中定义  
    // 不合法:不能再这里定义其他字段  
    // private final String address; // 这将导致编译错误  
    // 可以添加额外的方法  
    public String introduce() {  
        return String.format("My name is %s and I am %d years old.", name, age);  
    }  
}  
public record Person(String name, int age) {  
    // 静态字段  
    private static final String DEFAULT_COUNTRY = "Unknown";  
    // 静态方法  
    public static Person createDefaultPerson() {  
        return new Person("Anonymous", 0);  
    }  
    // 静态内部类  
    public static class PersonBuilder {  
        private String name;  
        private int age;  
        public PersonBuilder withName(String name) {  
            this.name = name;  
            return this;  
        }  
        public Person build() {  
            return new Person(name, age);  
        }  
    }  
    // 实例方法  
    public String introduce() {  
        return name + " is " + age + " years old";  
    }  
}  
// 使用示例  
public class Main {  
    public void example() {  
        // 使用静态方法  
        Person defaultPerson = Person.createDefaultPerson();  
        // 使用静态内部类  
        Person customPerson = new Person.PersonBuilder()  
            .withName("John")  
            .build();  
    }  
}  

五、总结:

5.1 场景使用

简单的数据使用

🌟 默认只有Getter方法

record Point(int x, int y) {
    // 无需显式定义构造器、equals()、hashCode() 或 toString()
}
public class Point {
    private final int x;
    private final int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Point point = (Point) o;
        return x == point.x && y == point.y;
    }
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

5.2 字段的定义

🌟 在 Java 记录中,所有字段都必须在记录的参数列表中定义。
🌟 记录是不可变的:字段一旦赋值,不能被修改。
🌟 无法在记录内部定义额外的 private final 字段。

下面是相关解释

隐式 final:

只能通过构造器定义:

自动构造器和访问器:

public record Person(String name, int age) {  
    // 这是合法的,因为字段在声明中定义  
    // 不合法:不能再这里定义其他字段  
    // private final String address; // 这将导致编译错误  
    // 可以添加额外的方法  
    public String introduce() {  
        return String.format("My name is %s and I am %d years old.", name, age);  
    }  
}  
// 使用记录的主函数  
public class Main {  
    public static void main(String[] args) {  
        Person person = new Person("Alice", 30);  
        System.out.println(person.introduce()); // 输出:My name is Alice and I am 30 years old.  
    }  
}

(后续有遇到问题再添加)

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

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