Java record类

4

since java 14

这点代码record Point(int x, int y) {}

编译后

final class Point extends Record {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int x() {
        return this.x;
    }

    public int y() {
        return this.y;
    }

    public String toString() {
        return String.format("Point[x=%s, y=%s]", x, y);
    }

    public boolean equals(Object o) {
        ...
    }
    public int hashCode() {
        ...
    }
}

也就是帮我们省去了很多繁琐的步骤

这样可以对默认的constructor进行函数的增加

public record Point(int x, int y) {
    public Point {
        //这部分会被加入到最终的constructor中
        if (x < 0 || y < 0) {
            throw new IllegalArgumentException();
        }
    }
}