java Lombok @Builder 不初始化集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32824821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:50:17  来源:igfitidea点击:

Lombok @Builder not initializing collections

javalombok

提问by marstran

I am using Lombok's @Dataand @Builderannotations like this:

我正在使用 Lombok@Data@Builder这样的注释:

@Data
@Builder(toBuilder = true)
class Movie {

    // Some other fields here.

    private final List<Actor> actors;

}

When I create a new Movieusing the builder, without specifying any actors, I would expect Lombok to initialize my List to Collections.emptyList(). But this does not happen:

当我Movie使用构建器创建一个新的时,没有指定任何演员,我希望 Lombok 将我的 List 初始化为Collections.emptyList(). 但这不会发生:

List<Actor> actors = Movie.builder().build().getActors();
System.out.println(actors); // Prints 'null'.

In the documentation for the @Builderannotation, 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.

@Builder注释的文档中,它在 Vanilla Java 的代码示例 ( https://projectlombok.org/features/Builder.html) 的第 55 和 56 行中说明,我应该查看@Singular( https: //projectlombok.org/features/Singular-snippet.html)。在此处的 Vanilla Java 示例的第 112 行,该列表似乎应该初始化为空列表。

I checked, and it does indeed happen if I annotate the list with @Singular:

我查了一下,如果我用以下内容注释列表,确实会发生@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 '[]'.

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 @Builderdoc refers to the @Singulardoc).

这是龙目岛的错误,还是我做错了什么?根据文档,在这两种情况下,列表似乎都应该初始化为空列表(因为@Builder文档指的是@Singular文档)。

回答by Roel Spilker

Only when you use @Singular, you get an empty list. On the Builder documentation pageit says:

只有当你使用时@Singular,你才会得到一个空列表。在Builder 文档页面上,它说:

…with the @Singularannotation, lombok will treat that builder node as a collection.

...使用@Singular注释,lombok 会将构建器节点视为一个集合。

Without the @Singular, lombok treats it as any other object. So it will be nullinstead of an empty Collection.

如果没有@Singular,lombok 会将其视为任何其他对象。所以它将null不是一个空的集合。

Disclosure: I am a Lombok developer

披露:我是龙目岛的开发人员