Initialize list if list is null with lombok getter?

I am currently replacing all my standard POJOs to use Lombok for all template code. I find that I am storing getters for lists because I want to return an empty list if the list has not been initialized. That is, I do not want getter to return null. If some kind of Lombok magic that I don’t know about can help me avoid this?

Sample Generated Code

private List<Object> list; public Object getList(){ return list; } 

Instead, I would like to:

 private List<Object> list; public Object getList(){ if (list == null) { return new ArrayList(); } return list; } 
+12
source share
4 answers

You can achieve this by declaring and initializing the fields. Initialization will be performed upon initialization of the surrounding object.

 private List<Object> list = new ArrayList(); 

Abstract Lomboks @Getter provides a lazy attribute that allows lazy initialization.

  @Getter(lazy=true) private final double[] cached = expensiveInitMethod(); 

Documentation

+7
source

I had the same questions as this one. While the answers above are useful in some ways, the exact solution is to use the @Builder and @Singular Lombok API annotations, like @Singular below in this code.

This worked perfectly for me.

 @Builder class MyClass{ @Singular private List<Type> myList; } 

This initializes myList with a nonzero List object. Although this question is old. But still posting this answer to help someone like me who will answer this question in the future

+6
source

That is, I do not want getter to return null. If some kind of Lombok magic that I don’t know about can help me avoid this?

You don't need magic to happen. Just initialize the list .

+1
source

You can override the recipient for anything using AccessLevel.NONE in the field.

Note that simply initializing the field does not protect you from clients calling the constructor with zero values ​​or calling the setter with zero values ​​(it may still be fine, depending on what you want).

for instance

 @Getter(AccessLevel.NONE) private Map<String, String> params; public Map<String, String> getParams() { return (params == null) ? new HashMap<>() : params; } 
+1
source

All Articles