参考fastjson.TypeReference的写法
import cn.hutool.core.lang.ParameterizedTypeImpl;
import cn.hutool.core.lang.TypeReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
// 参考fastjson.TypeReference,只取有用部分,减少包的引用和使用时的选择
public class CustomTypeReference<T> extends TypeReference<T> {
static ConcurrentMap<Type, Type> classTypeCache = new ConcurrentHashMap<>(16, 0.75F, 1);
private final Type customType;
public CustomTypeReference(Class<?>... actualTypeArguments) {
Class<?> thisClass = this.getClass();
Type superClass = thisClass.getGenericSuperclass();
ParameterizedType argType = (ParameterizedType) ((ParameterizedType) superClass).getActualTypeArguments()[0];
Type rawType = argType.getRawType();
Type[] argTypes = argType.getActualTypeArguments();
int actualIndex = 0;
for (int i = 0; i < argTypes.length; ++i) {
if (argTypes[i] instanceof TypeVariable && actualIndex < actualTypeArguments.length) {
argTypes[i] = actualTypeArguments[actualIndex++];
}
if (argTypes[i] instanceof ParameterizedType) {
argTypes[i] = this.handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);
}
}
Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);
Type cachedType = classTypeCache.get(key);
if (cachedType == null) {
classTypeCache.putIfAbsent(key, key);
cachedType = classTypeCache.get(key);
}
this.customType = cachedType;
}
@Override
public Type getType() {
return this.customType;
}
private Type handlerParameterizedType(ParameterizedType type, Type[] actualTypeArguments, int actualIndex) {
Class<?> thisClass = this.getClass();
Type rawType = type.getRawType();
Type[] argTypes = type.getActualTypeArguments();
for (int i = 0; i < argTypes.length; ++i) {
if (argTypes[i] instanceof TypeVariable && actualIndex < actualTypeArguments.length) {
argTypes[i] = actualTypeArguments[actualIndex++];
}
if (argTypes[i] instanceof ParameterizedType) {
argTypes[i] = this.handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);
}
}
return new ParameterizedTypeImpl(argTypes, thisClass, rawType);
}
}
使用CustomTypeReference
public PageResponse<T> getPage(Class<T> tClass) { return JSONUtil.toBean(this.data,new CustomTypeReference<PageResponse<T>>(tClass) { }, true); }