英文:
Default value for Lombok @Value without @Builder
问题
在用 @Value
注解标记的模型下,是否有一种方法为字段提供默认值呢?
例如:
@Value
class Book {
String title;
List<String> authors;
}
在上面的模型中,Jackson 将从具有 null
作者的 JSON 负载反序列化为 null
,但我希望作者具有 []
作为默认值,而不是 null
。
我知道以下方式行不通,因为由于 @Value
,字段会变成 private final
:
List<String> authors = Collections.emptyList();
我可以重写所有参数构造函数,但模型本身相当庞大,因此我正在寻找类似于 Builder.Default
的东西,但适用于 @Value
。
英文:
Is there a way to provide default value for fields under model annotated with @Value
.
For example:
@Value
class Book {
String title;
List<String> authors;
}
In above model, Jackson deserializes authors to null
from json payload that has authors as null
, but I want author to have a []
as default value as opposed to null
.
I know below won't work because field becomes private final
due to @Value
List<String> authors = Collections.emptyList();
I could override the all args constructor but the model itself is quite large so I am looking for something similar to Builder.Default
but for @Value
.
答案1
得分: 1
你可以添加自己的构造函数来初始化你的 authors
字段。
@Value
@AllArgsConstructor
static class Book {
String title;
List<String> authors;
public Book(String title) {
this(title, Collections.emptyList());
}
}
由于添加了自定义构造函数,需要使用 @AllArgsConstructor
注解,以便 @Value
不会生成所有字段的构造函数。
英文:
You can add your own constructor which initializes your authors
field.
@Value
@AllArgsConstructor
static class Book {
String title;
List<String> authors;
public Book(String title) {
this(title, Collections.emptyList());
}
}
@AllArgsConstructor
was required as, when a custom constructor was added, @Value
skipped all field constructor generation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论