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

标签 java lombok intellij-lombok-plugin

有一个包含类 B 的简单类 A,是否有任何 lombok 注释可以在 a 为 null 的情况下创建类 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 问题于 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.

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

关于java - 有没有办法让lombok在使用@Getter @Setter注释时在null的情况下创建一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38074886/

相关文章:

eclipse - Project Lombok 与 Eclipse 模板/代码生成

java - 当我使用 lombok 时,如何向 Gson 序列化/反序列化中具有空字符串值的传入变量添加默认值?

java - lombok 1.18.2 抛出 transformClassesWithDexBuilderForDebug

具有下限类型的 Java 类型推断

java - 如何为多个数据源创建/配置 Spring Actuator?

java - 如何将 boolean 值从主 Activity 发送到基本适配器

java - 真实世界的用户代理——它们是什么?如何设置它们? - java

java - 我可以从 lomboks @Data 注释中排除字段吗?

java - 在这里使用@lombok.Cleanup的正确方法是什么?

java - 如何在intellij-idea中为lombok生成的方法构建调用层次结构