Вызывающий:
Код: Выделить всё
public Features findFeatureById(BigDecimal id) {
return mixedCacheService.get(FEATURE, id.toString(), new MixedCacheService.Func(() -> featuresDao.selectById(id)));
}
Код: Выделить всё
public T get(@NotNull CacheBaseConstants cacheBaseConstants, @NotNull String key, @NotNull Supplier getter) {
String value = get(cacheBaseConstants, key);
if ("".equals(value)) {
return null;
}
// How can I get T.class here?
return Optional.ofNullable(value)
.map(o -> JSON.parseObject(value, T.class))
.orElseGet(() -> put(cacheBaseConstants, key, getter));
}
Код: Выделить всё
public static class Func extends TypeReference {
private Supplier supplier;
public Func(Supplier supplier) {
super();
this.supplier = supplier;
}
public T get() {
return supplier.get();
}
}
рецепт
Код: Выделить всё
import cn.hutool.core.lang.TypeReference;
import java.util.function.Supplier;
public abstract class SupplierProxy extends TypeReference {
private final Supplier supplier;
public SupplierProxy(Supplier supplier) {
super();
this.supplier = supplier;
}
public T get() {
return supplier.get();
}
}
Код: Выделить всё
@Test
public void get() {
Features actual = new Features();
actual.setName("123");
assertEquals(actual,mixedCacheService.get(FEATURE_BY_KEY, "1", new SupplierProxy(() -> actual) {
}));
assertEquals( actual,mixedCacheService.get(FEATURE_BY_KEY, "1", new SupplierProxy(() -> actual) {
}));
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... od-in-java