Lombok @Builder未初始化集合 [英] Lombok @Builder not initializing collections
问题描述
我正在使用Lombok的 @Data
和 @Builder
注释,如下所示:
I am using Lombok's @Data
and @Builder
annotations like this:
@Data
@Builder(toBuilder = true)
class Movie {
// Some other fields here.
private final List<Actor> actors;
}
当我使用构建器创建新的 Movie
而不指定任何参与者时,我希望Lombok将我的列表初始化为 Collections.emptyList()
.但这不会发生:
When I create a new Movie
using the builder, without specifying any actors, I would expect Lombok to initialize my List to Collections.emptyList()
. But this does not happen:
List<Actor> actors = Movie.builder().build().getActors();
System.out.println(actors); // Prints 'null'.
在 @Builder
批注的文档中,在Vanilla Java的代码示例( https://projectlombok.org/features/Singular-snippet.html ).在此处的Vanilla Java示例的第112行,似乎列表应该初始化为空列表.
In the documentation for the @Builder
annotation, it is stated at line 55 and 56 in the code-example for Vanilla Java (https://projectlombok.org/features/Builder.html) that I should look at the code example for @Singular
(https://projectlombok.org/features/Singular-snippet.html). At line 112 in the Vanilla Java example here, it seems like the list should be initialized to the empty list.
我检查了一下,如果我用 @Singular
注释列表,确实会发生这种情况:
I checked, and it does indeed happen if I annotate the list with @Singular
:
@Data
@Builder(toBuilder = true)
class Movie {
// Some other fields here.
@Singular
private final List<Actor> actors;
}
List<Actor> actors = Movie.builder().build().getActors();
System.out.println(actors); // Prints '[]'.
这是Lombok中的错误,还是我做错了什么?根据文档,似乎在两种情况下都应将列表初始化为空列表(因为 @Builder
文档是指 @Singular
文档).>
Is this a bug in Lombok, or is there something that I am doing wrong? According to the documentation, it seems like the list should be initialized to the empty list in both cases (because the @Builder
doc refers to the @Singular
doc).
推荐答案
仅当使用 @Singular
时,您会得到一个空列表.在构建器文档页面上,它说:
Only when you use @Singular
, you get an empty list. On the Builder documentation page it says:
…带有
@Singular
批注,lombok会将该构建器节点视为一个集合.
…with the
@Singular
annotation, lombok will treat that builder node as a collection.
在没有 @Singular
的情况下,lombok将其视为任何其他对象.因此它将是 null
而不是空的Collection.
Without the @Singular
, lombok treats it as any other object. So it will be null
instead of an empty Collection.
披露:我是Lombok开发人员
Disclosure: I am a Lombok developer
这篇关于Lombok @Builder未初始化集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!