gpt4 book ai didi

java - 在条件构造函数上使用 @RequiredArgsConstructor

转载 作者:行者123 更新时间:2023-12-02 08:42:34 28 4
gpt4 key购买 nike

我正在使用 Lombok 移动整个项目中所有硬编码的公共(public)/私有(private)构造函数。这是一个特殊的用例,其中有两个成员变量。但在构造函数中传递一个参数作为参数来设置属性。在这种情况下如何使用@RequiredArgsConstructor:

如何使用 @RequiredArgsConstructor 来转换此构造函数?

public ObjectToString(final String delimiter) {
this.delimiter = delimiter;
this.functions = new ArrayList<>();
}

类模板:

public final class ObjectToString {

private final String delimiter;
private final List<String> functions;

public ObjectToString(final String delimiter) {
this.delimiter = delimiter;
this.functions = new ArrayList<>();
}

public ObjectToString add(final List<String> func) {
functions.add(func);
return this;
}
///Next lines follows the class implementation code.
}

最佳答案

尝试这样:

@RequiredArgsConstructor
public final class ObjectToString {

private final String delimiter;
private final List<String> functions = new ArrayList<>();

public ObjectToString add(final List<String> func) {
functions.add(func);
return this;
}

// Rest excluded

}

在您的情况下,无需在构造函数中创建数组列表。如果您像这样初始化字段,lombok 将不会在构造函数中为其创建参数。

lombok 文档的相关部分:

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. From: https://projectlombok.org/features/constructor

关于java - 在条件构造函数上使用 @RequiredArgsConstructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61280053/

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