siebz0r siebz0r - 5 months ago 21
Java Question

Lombok lazy getter for mutable collections

I have a class which has a collection:

public class Foo
{
@Inject
private BarManager barManager;
@Getter(lazy = true)
private final List<Bar> bars = barManager.getAll();

public void addBar(Bar bar)
{
bars.add(bar);
}
}


However I cannot add/remove elements to/from the
List
. The cause is that the attribute is an
AtomicReference
. The warning/error is:

The method add(Employee) is undefined for the type AtomicReference<AtomicReference<List<Employee>>>


How can perform add/remove operations on the collection?

Answer

Your solution is weird indeed and depends on some implementation details. Moreover it break with NPE if the field hasn't been initialized yet. The proper solution works always:

getBars().add(bar);