开发者

Is there a class for lazily computed values somewhere in the popular/standard Java libraries?

I'm wondering whether there is a "standard" class somewhere (JDK, Guava, Apache *), that would help with the lazy initialization/computation pattern?

I'm thinking about something like this (let's ignore synchronization for now):

abstract class Lazy<T> {
  T instance = null;
  protected T compute();
  final T get() {
    if (instance == null) instance = compute();
    return instance;
  }
}

//...

Lazy<Foo> foo = new Lazy<Foo> {
  protected Foo compute() { return Foo.expensivePart(); }
}

//...

Bar bar =开发者_如何转开发 foo.get().getBar();


If I understand you right, then Lombok will do the job with a single annotation @Getter(lazy=true).

(Lombok also offers some further very useful annotations, such as @Delegate, @EqualsAndHashCode, @Synchronized).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜