USer22999299
USer22999299

Reputation: 5674

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

Having a simple class A that contains class B is there any lombok annotation that will create new instance of class b in a in case of null?

public class A {

   @Getter
   @Setter
   private B b;

}

Upvotes: 1

Views: 3135

Answers (1)

Magnilex
Magnilex

Reputation: 11958

I am afraid the feature doesn't exist. The documenation lists a number of configuration keys for the annotations, but the functionality you are after is not listed.

Somebody recently asked for something like this on the Lombok GitHub page:

I'd love this feature for this scenario:

@Getter(lazy = true) private List<String> foo = new ArrayList<>(); to generate something like this:

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.

So, the feature is not (yet?) implemented. If I were you, I would avoid using the annotation in these cases, and instead create the methods wanted by hand.


The GitHub issue was parked on 20 February 2020. Part of the motivation is as follows:

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.

I guess this makes it even more unlikely that the feature will be implemented.

Upvotes: 5

Related Questions