Ido Kahana
Ido Kahana

Reputation: 321

JAVA annotaion for cache on access

are there is some java annotaion that will allow me to ignore code repet such as

private ISource source;

public ISource getSource() {
    return source == null ? source = ... : source;
}

private IProduct product;

public IProduct getProduct() {
    return product == null ? product = ... : product;
}

private IFoo foo;

public IFoo getFoo() {
    return foo == null ? foo = ... : foo;
}

Upvotes: 0

Views: 116

Answers (1)

Adam Gent
Adam Gent

Reputation: 49095

The issue would be how you want to create the objects particularly since they appear to be interfaces and how you create those objects is probably fairly custom.

As @OliverCharlesworth mentioned you could use a memoized supplier. With Java 8 lambdas it is rather terse. You then could make a custom annotation on a supplier field and write your own APT plugin (see Google's auto project for some examples)

e.g.

@SupplierToGetter
private final Supplier<ISource> source = Suppliers.memoize( -> new Source());

Otherwise one option is just to make the supplier fields as public and not bother generating a getter:

public final Supplier<ISource> source = Suppliers.memoize( -> new Source());

BTW the memoize will be thread safe unlike foo == null ? foo = ....

EDIT after comment:

The Java 7 version would be (using Guava):

public final Supplier<ISource> source = Suppliers.memoize( new Supplier<ISource>() { 
    public ISource get() { return new Source(); }
});

Upvotes: 2

Related Questions