龙目岛 我们可以在单个类上同时使用@Builder和@Value吗?

2022-09-02 03:29:45

首先,多亏了龙目岛,我们的java代码现在更加时尚和干净。我的用例是我想创建一个不可变的类。为此,我会使用@Value注释。另外,我想使用构建器功能,为此我将使用@Builder注释。我的问题是,我们是否可以在单个类上同时使用@Builder和@Value。这是龙目岛用户/开发人员推荐的好习惯吗?


答案 1

当然可以。要进行检查,只需对代码进行 delombok 并查看它生成的内容。举个例子:

@Builder
@Value
public class Pair {
    private Object left;
    private Object right;
}

去聚类后,这会产生:

public class Pair {
    private Object left;
    private Object right;

    @java.beans.ConstructorProperties({ "left", "right" })
    Pair(Object left, Object right) {
        this.left = left;
        this.right = right;
    }

    public static PairBuilder builder() {
        return new PairBuilder();
    }

    public Object getLeft() {
        return this.left;
    }

    public Object getRight() {
        return this.right;
    }

    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof Pair)) return false;
        final Pair other = (Pair) o;
        final Object this$left = this.left;
        final Object other$left = other.left;
        if (this$left == null ? other$left != null : !this$left.equals(other$left)) return false;
        final Object this$right = this.right;
        final Object other$right = other.right;
        if (this$right == null ? other$right != null : !this$right.equals(other$right)) return false;
        return true;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $left = this.left;
        result = result * PRIME + ($left == null ? 0 : $left.hashCode());
        final Object $right = this.right;
        result = result * PRIME + ($right == null ? 0 : $right.hashCode());
        return result;
    }

    public String toString() {
        return "Pair(left=" + this.left + ", right=" + this.right + ")";
    }

    public static class PairBuilder {
        private Object left;
        private Object right;

        PairBuilder() {
        }

        public Pair.PairBuilder left(Object left) {
            this.left = left;
            return this;
        }

        public Pair.PairBuilder right(Object right) {
            this.right = right;
            return this;
        }

        public Pair build() {
            return new Pair(left, right);
        }

        public String toString() {
            return "Pair.PairBuilder(left=" + this.left + ", right=" + this.right + ")";
        }
    }
}

因此,您可以清楚地同时使用和@Value@Builder


答案 2

从版本 1.16.10 开始,构造函数在同时使用两者时不是公共的。

您可以添加@AllArgsConstructor来弥补这一点。


推荐