如何使用lombok配置getter-only-lazy-initializing collection字段?

时间:2015-11-10 16:22:10

标签: java collections getter lazy-initialization lombok

如何使lombok生成以下getter方法?

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

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

    return students;
}

private List<Student> students;

一个简单的@Getter会这样做吗?

1 个答案:

答案 0 :(得分:2)

我不确定这是否是一种正确的方法。

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

lombok生成以下方法。

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