简体   繁体   English

龙目岛懒惰的可变集合的吸气剂

[英]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 . 但是我无法在List添加/删除元素。 The cause is that the attribute is an AtomicReference . 原因是该属性是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. 此外,如果该领域尚未初始化,它会与NPE决裂。 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. get()返回引用,但由于某种原因,我必须调用get()两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM