Lombok Lazy Getter para colecciones mutables
Frecuentes
Visto 1,638 veces
1
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?
2 Respuestas
3
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);
Respondido 28 ago 12, 18:08
1
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);
}
}
Programas de get()
returns the reference, however for some reason I have to call get()
dos veces.
Respondido el 28 de junio de 16 a las 08:06
In the future we plan to change the implementation of the generated code for lazy getters to no longer use AtomicReference-s. So you shouldnot depend on it, and use getBars() instead. Disclaimer: I am one of the Project Lombok developers. - roel desplumador
We do no longer have concrete plans to change this. That does not change the fact that you should just use getBars()
, and not depend on internal behavior. - roel desplumador
The current implementation no longer generates the double AtomicReference. Use the getter. But If you must, currently, if bars.get() == bars
you should replace it by null
. Usamos null
to state uninitialized, and bars
to mask null. - roel desplumador
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java collections lombok or haz tu propia pregunta.
I actually never thought of calling the getter. Sometimes the solution isn't that difficult. :-) - siebz0r