有没有办法让 lombok 在使用 @Getter @Setter 注释时在 null 的情况下创建对象?

Is there a way to make lombok to create an object in case of null while using @Getter @Setter annotation?

有一个包含 class B 的简单 class A 是否有任何 lombok 注释可以在 null 的情况下在 a 中创建 class b 的新实例?

public class A {

   @Getter
   @Setter
   private B b;

}

恐怕该功能不存在。 documenation 列出了注释的许多配置键,但未列出您想要的功能。

最近有人在 Lombok GitHub page:

上提出了这样的要求

I'd love this feature for this scenario:

@Getter(lazy = true) private List<String> foo = new ArrayList<>(); 生成这样的东西:

private List<String> foo;
public List<String> getFoo() {
    if (this.foo == null) {
        this.foo == new ArrayList<>();
    }
    return this.foo;
}

Of course, it could use the double-checked locking or an AtomicReference, but the point here is I'd rather get an empty list than a null reference. It's a common idiom in JAXB classes for instance which are nice to reduce in size with Lombok.

因此,该功能尚未(尚未?)实施。如果我是你,我会避免在这些情况下使用注释,而是手动创建所需的方法。


GitHub issue 停在2020年2月20日。部分the motivation如下:

Also, it'd mean that calling a getter has a clear observable side effect and that sounds like a very bad idea. The current impl of lazy getter is fine because the field cannot pragmatically be accessed in the first place, and the getter appears to be idempotent. This in contrast to your proposal, where the field remains accessible.

我想这使得该功能更不可能实现。