Question

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?

Était-ce utile?

La solution

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);

Autres conseils

Disclaimer: This answer and especially the comments are here for informational purposes. Please use the accepted answer above instead of this.


Wouldn't have thought to solve it so quickly by myself. The solution is rather weird:

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

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

The get() returns the reference, however for some reason I have to call get() twice.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top