protected TypeToken() {
this.type = getSuperclassTypeParameter(getClass());
//获取到泛型类的类型
this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
this.hashCode = type.hashCode();
}
/**
* Returns the type from super class's type parameter in {@link $Gson$Types#canonicalize
* canonical form}.
*/
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
//如果泛型没有相应的类型,那么抛出异常
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
/**
* Returns the {@code Type} that represents the superclass of this {@code
* class}.
*/
public Type getGenericSuperclass() {
Type genericSuperclass = getSuperclass();
// This method is specified to return null for all cases where getSuperclass
// returns null, i.e, for primitives, interfaces, void and java.lang.Object.
if (genericSuperclass == null) {
return null;
}
String annotationSignature = AnnotationAccess.getSignature(this);
if (annotationSignature != null) {
GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
parser.parseForClass(this, annotationSignature);
genericSuperclass = parser.superclassType;
}
return Types.getType(genericSuperclass);
}
该函数的具体作用可以参考stackoverflow中的泛型存储举例
http://stackoverflow.com/questions/937933/where-are-generic-types-stored-in-java-class-files
TypeToken源码阅读
最新推荐文章于 2023-04-08 20:00:00 发布