gpt4 book ai didi

java - Lombok 我们可以在一个类上同时使用@Builder 和@Value吗

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:07 25 4
gpt4 key购买 nike

首先要感谢 Lombok,我们的 Java 代码现在更加简洁明了。我的用例是我想创建一个不可变的类。为此,我会使用@Value 注释。我还想使用构建器功能,为此我会使用 @Builder 注释。我的问题是我们是否可以在一个类上同时使用@Builder 和@Value。这是 Lombok 用户/开发人员推荐的好做法吗?

最佳答案

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

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

在 delombokification 之后,这会产生:

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

关于java - Lombok 我们可以在一个类上同时使用@Builder 和@Value吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com