有一个包含类 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/