Lombok的@Value注解的默认值,不使用@Builder注解

huangapple go评论60阅读模式
英文:

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&lt;String&gt; 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&lt;String&gt; 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&lt;String&gt; 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.

huangapple
  • 本文由 发表于 2020年10月22日 03:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64470219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定