出现异常的代码(省略了与本文无关的代码)
package utils;
import org.apache.commons.javaflow.utils.ReflectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import play.Play;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class RedisClient {
/* 封装好的redis util方法。。。*/
public static <T> T queryByCache(String key, RedisCacheQuery<T> cacheQuery) throws IOException {
int second = 24 * 60 * 60;
String value = getAndExpireIfPresent(key, second);
T result;
if (value == null) {
result = cacheQuery.queryDatabase();
value = JsonHelper.toString(result);
setAndExpire(key, value, second);
}else {
// 这里是调用了工具类方法,内部实现为jackson
// ObjectMapper.readValue()
result = JsonHelper.fromString(value, cacheQuery.getGenericClass());
}
return result;
}
public interface RedisCacheQuery<T> {
@SuppressWarnings("unchecked")
default Class <T> getGenericClass() {
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
return (Class)params[0];
}
T queryDatabase();
}
}
调用方法,使用了lambda
public static void getAllCountry() throws Exception {
List list = RedisClient.queryByCache(REDIS_KEY,
()-> dataService.findAllGeoCountryIso();
});
ok(list);
}
然后调用时出现异常,然后百度了很多错误分析,有一篇分析的很好,https://www.cnblogs.com/GaiDynasty/p/3938288.html,但是这篇文章是以hibernate.baseDao介绍的,不符合我的要求。
但是里面的一句话给了我启发:范式应该在编译的时候就指定,而不是运行时。
我猜想是不是动态的lambda造成的? 去查了相关的lambda资料,也没有很明白的介绍,于是就根据自己的想法修改,用回了匿名类,发现果然比lambda要好些,然后一步一步debug,因为时间关系,具体步骤就不上了,最终OK代码如下(只贴了interface):
public interface RedisCacheQuery<T> {
@SuppressWarnings("unchecked")
default Class <T> getGenericClass() {
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericInterfaces()[0];
Type type = parameterizedType.getActualTypeArguments()[0];
return (Class<T>) (type instanceof Class ? type : ((ParameterizedType) type).getRawType());
}
T queryDatabase();
}