문제

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