Method method = ((MethodSignature) pjp.getSignature()).getMethod();
Object[] args = pjp.getArgs();
//根据方法注解和参数获取缓存的key,
String key = GenerateKeyUtil.getCacheKey(method, args);
String cacheJson = redisTemplate.opsForValue().get(key);
Class> returnType = method.getReturnType();
return objctMapper.readValue(cacheJson,returnType);
如果method的返回类型是List
后来看了一下jackson的代码注释,使用下列方法可以通用的解析json数据为带泛型的结果;
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
Object[] args = pjp.getArgs();
//根据方法注解和参数获取缓存的key,
String key = GenerateKeyUtil.getCacheKey(method, args);
//获取redis缓存的值,
String cacheJson = redisTemplate.opsForValue().get(key);
//带有泛型信息
Type genericReturnType = method.getGenericReturnType();
//获取返回类的绑定信息
JavaType javaType = JsonUtil.getJavaType(genericReturnType);
return objectMapper.readValue(cacheJson,javaType);
下面是JsonUtil.getJavaType(Type type)的代码
public static JavaType getJavaType(Type type) {
//判断是否带有泛型
if (type instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
//获取泛型类型
Class rowClass = (Class) ((ParameterizedType) type).getRawType();
JavaType[] javaTypes = new JavaType[actualTypeArguments.length];
for (int i = 0; i < actualTypeArguments.length; i++) {
//泛型也可能带有泛型,递归获取
javaTypes[i] = getJavaType(actualTypeArguments[i]);
}
return TypeFactory.defaultInstance().constructParametricType(rowClass, javaTypes);
} else {
//简单类型直接用该类构建JavaType
Class cla = (Class) type;
return TypeFactory.defaultInstance().constructParametricType(cla, new JavaType[0]);
}
}
上面的方法经过测试可以解析任意层数,但是是递归实现,搞了半天没搞出来循环方式实现。
有循环实现的求评论个链接或则代码。。。
另外把TypeFactory.constructParametricType()的源码注释贴下面
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. For example, to represent
* type List>
, you could
* call
*
* JavaType inner = TypeFactory.constructParametricType(Set.class, Set.class, Integer.class);
* return TypeFactory.constructParametricType(ArrayList.class, List.class, inner);
*
*
* The reason for first two arguments to be separate is that parameterization may
* apply to a super-type. For example, if generic type was instead to be
* constructed for ArrayList
, the usual call would be:
*
* TypeFactory.constructParametricType(ArrayList.class, List.class, Integer.class);
*
* since parameterization is applied to {@link java.util.List}.
* In most cases distinction does not matter, but there are types where it does;
* one such example is parameterization of types that implement {@link java.util.Iterator}.
*
* NOTE: type modifiers are NOT called on constructed type.
*
* @param rawType Actual type-erased type
* @param parameterTypes Type parameters to apply
*
* @since 2.5 NOTE: was briefly deprecated for 2.6
*/
觉得有用点个赞。