Lombok @Builder 不会创建不可变对象?

Lombok @Builder does not create immutable objects?

在很多网站上,我看到lombok @Builder 可以用来创建不可变对象(https://www.baeldung.com/lombok-builder-singular),还有很多网站说Builder模式主要用于创建不可变对象。

TimeIntervalData td = TimeIntervalData.builder().endTime("12:00").startTime("10:00").build();
td.setEndTime("14:00");
System.out.println(td.getEndTime());

我不确定如何在使用构建器构建的对象上使用设置器。我在这里遗漏了什么吗?

是的,lombok 构建器不会创建不可变实例,但用户将 class 中的参数定义为 final,根据 lombok.builder @Builder 中的文档,您可以自动生成使您的 class 可用代码实例化所需的代码,例如:

Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();

根据文档,它只是以与外部 class

中提到的相同的方式创建具有相同属性的内部静态 class

A method annotated with @Builder (from now on called the target) causes the following 7 things to be generated:

  • 一个名为 FooBuilder 的内部静态 class,具有与静态方法(称为生成器)相同的类型参数。
  • 在构建器中:目标的每个参数都有一个私有非静态非最终字段。
  • 在构建器中:包私有无参数空构造函数。
  • 在构建器中:目标的每个参数都有一个类似于'setter'的方法:它与该参数具有相同的类型和相同的名称。它 returns 构建器本身,因此可以链接 setter 调用
  • 在构建器中:调用方法的 build() 方法,传入每个字段。它 returns 与目标 returns
  • 的类型相同
  • 在构建器中:一个合理的 toString() 实现。
  • 在包含目标的 class 中:一个 builder() 方法,它创建一个新的构建器实例。

但是使用带有 @Builder 注释的 @Singular 集合属性会使它们成为单例

By annotating one of the parameters (if annotating a method or constructor with @Builder) or fields (if annotating a class with @Builder) with the @Singular annotation, lombok will treat that builder node as a collection, and it generates 2 'adder' methods instead of a 'setter' method. One which adds a single element to the collection, and one which adds all elements of another collection to the collection. No setter to just set the collection (replacing whatever was already added) will be generated.

@Singular can only be applied to collection types known to lombok.

is mainly used to create immutable objects

这种说法是不正确的。主要目的是减少样板代码。使用构建器创建对象更紧凑,更易于编写和阅读。

当您有 1-2 个属性时,构建器可能处于不利地位,与通过构造函数传递参数相比,它会使代码的可读性降低。

所以何时使用或不使用构建器是个人喜好问题。

致setter:如果需要setter,可以通过@Data注解生成。