Lombok 之 @Getter(lazy=true)

LomBok 的相关目录已经整理出来,希望大家可以根据需求自助学习,好工具要大家分享:

@Cleanup     

@Getter, @Setter

@ToString

@EqualsAndHashCode

@Constructor

@Data & @Value

@SneakyThrows

@Synchronized

@Getter(lazy=true)

@Log

最后终于到了一个高级点的annotation的用法了,使用lazy版的getter  annotation, 会提高代码效率,同时由Lombok帮助你管理线程安全问题,大可放心。先看一段代码:

import lombok.Getter;

public class GetterLazyExample {
  @Getter(lazy=true) private final double[] cached = expensive();
  
  private double[] expensive() {
    double[] result = new double[1000000];
    for (int i = 0; i < result.length; i++) {
      result[i] = Math.asin(i);
    }
    return result;
  }
}

使用了getter这个annotation可以在实际使用到cached的时候生成cached,同时,Lombok会自动去管理线程安全的问题,不会存在重复赋值的问题。

可以把这篇博客作为之前一篇@Getter的一个附属特性。Getter还真是蛮好用的。

猜你喜欢

转载自himichaelchu.iteye.com/blog/2124588
今日推荐