[英]Java 8 Lambda for Anonymous Class
I have a tricky situation here, which I would like to optimize from the code perspective. 我这里有一个棘手的情况,我想从代码角度进行优化。 Is there any way to shorten the following method via Lambda / Java8 expressions?
是否可以通过Lambda / Java8表达式缩短以下方法?
// total amount of audiences
registry.register("metric.persons.total", new CachedGauge<Integer>(1,TimeUnit.MINUTES) {
@Override
protected Integer loadValue() {
return personService.findAll().size();
}
});
The CachedGauge class is looking like this: CachedGauge类看起来像这样:
public abstract class CachedGauge<T> implements Gauge<T> {
protected CachedGauge(long timeout, TimeUnit timeoutUnit) {
...
}
protected abstract T loadValue();
...
}
}
Would be really great to see if there is a way, the tricky part here is that there is a default constructor and the class is parameterized. 真的很高兴看看是否有办法,这里的棘手部分是有一个默认的构造函数,并且该类已参数化。
best, fri 最好,星期五
registry.register("metric.persons.total",
CachedGauge.of(1,TimeUnit.MINUTES, ()->personService.findAll().size() )
);
And I think you can figure out how to implement CachedGauge.of(long, TimeUnit, Supplier<T>)
而且我认为您可以弄清楚如何实现
CachedGauge.of(long, TimeUnit, Supplier<T>)
Just for completion of this thread, my Utils class looks like this 只是为了完成该线程,我的Utils类看起来像这样
public class MetricUtils {
public static <T> CachedGauge<T> cachedGauge(long timeout, TimeUnit timeoutUnit, Supplier<T> supplier) {
return new CachedGauge<T>(timeout, timeoutUnit) {
@Override
protected T loadValue() {
return supplier.get();
}
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.