I am currently replacing all my standard POJO's to use Lombok for all the boilerplate code. I find myself keeping getters for lists because I want to return an empty list if the list has not been initialized. That is, I don't want the getter to return null. If there some lombok magic that I'm not aware of that can help me avoid doing this?
Example of generated code
private List<Object> list;
public Object getList(){ return list; }
What I would like instead:
private List<Object> list;
public Object getList(){
if (list == null) {
return new ArrayList();
}
return list;
}
From Lombok documentation: You can always manually disable getter/setter generation for any field by using the special AccessLevel. NONE access level. This lets you override the behaviour of a @Getter, @Setter or @Data annotation on a class.
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.
Bookmark this question. Show activity on this post. Using lombok for a project, I have an ArrayList. It's null because it's never initialized. I originally initialized this in the constructor before I decided to use lombok to remove the bulk of boilerplate code.
The docs say that the list would be immutable. Yeah but the collection is still null inside of the POJO. 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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With