【问题标题】:How can I configure getter-only-lazy-initializing collection field with lombok?如何使用 lombok 配置 getter-only-lazy-initializing 集合字段?
【发布时间】:2015-11-10 16:22:09
【问题描述】:

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

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

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

    return students;
}

private List<Student> students;

一个简单的@Getter 能做到吗?

【问题讨论】:

    标签: java collections getter lazy-initialization lombok


    【解决方案1】:

    我不确定这是否是正确的做法。

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

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2016-05-26
      • 2017-07-25
      • 1970-01-01
      • 2017-03-15
      • 2017-07-04
      • 2022-08-19
      • 1970-01-01
      • 2021-03-02
      相关资源
      最近更新 更多