Initialize list if list is null with lombok getter?
I had the same questions as of this one. Though, the above answers are useful in some ways, the exact solution is to use @Builder
and @Singular
annotations of Lombok API like below given code.
It worked superb for me.
@Builder
class MyClass{
@Singular
private List<Type> myList;
}
This will initialize myList with a non-null List object. Though, this questions is an old one. But, still posting this answer to help someone like me who will refer this question in future.
Newest versions of lombok do not generate a getter method if a getter method is provided with the same name and number of parameters.
With older versions of lombok, you can override the getter with anything you like by using AccessLevel.NONE on the field.
Note that merely initializing the field does not protect you from clients calling a constructor with nulls, or calling a setter with null (Still may be okay, depending on what you want).
E.g.
// only necessary for older versions of lombok
@Getter(AccessLevel.NONE)
private Map<String, String> params;
public Map<String, String> getParams() {
return (params == null) ? new HashMap<>() : params;
}
You can achieve this by declaring and initializing the fields. The initialization will be done when the enclosing object is initialized.
private List<Object> list = new ArrayList();
Lomboks @Getter
annotation provides an attribute lazy
which allows lazy initialization.
@Getter(lazy=true) private final double[] cached = expensiveInitMethod();
Documentation