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?

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top