// 底口 publicstaticfinal <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features){ // 省略转换和校验代码... T value = (T) parser.parseObject(clazz);
handleResovleTask(parser, value);
parser.close();
return (T) value; }
我们在最底层的方法中发现了一句话T value = (T) parser.parseObject(clazz);这里传进来的clazz对象是java.lang.reflect.Type类型的,大家可以看一下这个类,很神奇,这里重点不是它,不做说明了。
/** * Constructs a new type literal. Derives represented class from type * parameter. * * <p>Clients create an empty anonymous subclass. Doing so embeds the type * parameter in the anonymous class's type hierarchy so we can reconstitute it * at runtime despite erasure. */ protectedTypeReference(){ Type superClass = getClass().getGenericSuperclass();
Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
Type cachedType = classTypeCache.get(type); if (cachedType == null) { classTypeCache.putIfAbsent(type, type); cachedType = classTypeCache.get(type); }
this.type = cachedType; }
代码中最核心的一句是Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];,这句话的意思是获得超类的泛型参数的实际类型,也就是获得泛型T的实际类型type。看到这里有点懵,到底我们获取到的type是什么?简单写一个case看下:
publicstaticvoidmain(String[] args){ // ① TypeReference reference = new TypeReference<ArrayList<String>>() { }; Type superClass = reference.getClass().getGenericSuperclass(); Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
System.out.println(type); // ② System.out.println((Type) (ArrayList.class)); }
}
输出结果为:
1 2
java.util.ArrayList<java.lang.String> class java.util.ArrayList