记录类(Record Class)的构造方法

在Java中,记录类(Record Class)是Java 14引入的一种特殊类型,用于创建不可变的数据容器。记录类的构造方法有几种写法:

1. 隐式构造方法

当你声明一个记录类时,编译器会自动生成一个规范构造方法(canonical constructor),它接收所有组件作为参数:

public record Person(String name, int age) {
    // 编译器自动生成的构造方法:
    // public Person(String name, int age) {
    //     [this.name](<http://this.name>) = name;
    //     this.age = age;
    // }
}

2. 显式规范构造方法

你可以显式定义规范构造方法,它必须接收所有组件作为参数:

public record Person(String name, int age) {
    // 显式定义规范构造方法
    public Person(String name, int age) {
        // 可以添加参数验证
        if (name == null) {
            throw new IllegalArgumentException("Name cannot be null");
        }
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        [this.name](<http://this.name>) = name;
        this.age = age;
    }
}

3. 紧凑构造方法

紧凑构造方法(compact constructor)是一种简化的构造方法,它不包含参数列表,主要用于验证和规范化参数:

public record Person(String name, int age) {
    // 紧凑构造方法
    public Person {
        if (name == null) {
            throw new IllegalArgumentException("Name cannot be null");
        }
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        // 不需要赋值语句,编译器会自动添加
    }
}

4. 自定义构造方法

你还可以定义其他构造方法,但它们必须调用规范构造方法或另一个构造方法:

public record Person(String name, int age) {
    // 自定义构造方法
    public Person(String name) {
        this(name, 0); // 调用规范构造方法
    }
}

注意事项

示例:组合使用不同类型的构造方法