Search code examples
javacollectionsgetterlazy-initializationlombok

How can I configure getter-only-lazy-initializing collection field with lombok?


How can I make lombok generates following getter method?

// getter only
// lazy initialization
public List<Student> getStudents() {

    if (students == null) {
        students = new ArrayList<Student>();
    }

    return students;
}

private List<Student> students;

Does a simple @Getter will do that?


Solution

  • I'm not sure if this is a proper way to do this.

    @Getter(lazy = true, @__({@XmlElement}))
    private final List<Student> students = new ArrayList<Student>();
    

    And lombok generates following method.

    @XmlElement
    @java.lang.SuppressWarnings("all")
    @javax.annotation.Generated("lombok")
    public List<Student> getStudents() {
        Object value = this.students.get();
        if (value == null) {
            synchronized (this.students) {
                value = this.students.get();
                if (value == null) {
                    final List<Student> actualValue = new ArrayList<Student>();
                    value = actualValue == null ? this.students : actualValue;
                    this.students.set(value);
                }
            }
        }
        return (List<Student>)(value == this.students ? null : value);
    }
    
    private final AtomicReference<Object> students = new AtomicReference<Object>();