使用Intellij和lombok插件版本203.5981.41,当我用delombok查看生成了什么代码时,我得不到lombok GetterLazy docs建议的AtomicReference:
@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;
}
在Intellij中生成以下代码:
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;
}
而不是像文档中建议的那样:
private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized(this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive();
value = actualValue == null ? this.cached : actualValue;
this.cached.set(value);
}
}
}
return (double[])(value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
显然,这不是懒惰的,所以使用有限,这是lombok对懒惰getter工作方式的改变,还是Delombok在Intellij中工作方式的错误?
或者我是不是做错了什么,应该实现我错过的其他东西/东西?
正如@chris指出的,问题出在intellij中的Lombok插件。
发布于 2021-01-23 20:21:53
这是IntelliJ Lombok插件的Delombok特性的一个限制。它似乎不能识别@Getter
上的lazy=true
。试着用下面这样的简单测试来验证这个行为,你会看到它像预期的那样工作:
public class LombokTests {
@Test
public void lazyGettersAreNotEagerlyCalled() {
var foobarCache = new FoobarCache();
assertThat(foobarCache.foobarFetchedTimes)
.describedAs("Lazy means lazy!")
.isEqualTo(0);
}
@Test
public void lazyGettersAreCalledOnlyOnce() {
var foobarCache = new FoobarCache();
System.out.println(foobarCache.getFoobar());
System.out.println(foobarCache.getFoobar());
assertThat(foobarCache.foobarFetchedTimes)
.describedAs("Repeated calls to lazy getter should be cached")
.isEqualTo(1);
}
static class FoobarCache {
@Getter(lazy = true)
private final String foobar = fetchFoobarFromSuperExpensiveExternalApi();
private int foobarFetchedTimes = 0;
private String fetchFoobarFromSuperExpensiveExternalApi() {
this.foobarFetchedTimes++;
return "foobar";
}
}
}
https://stackoverflow.com/questions/65021120
复制相似问题