一、fastjson解析参数化类型对象
先看一个使用fastjson解析参数类型对象的例子:
public static void main(String ... args) {
String personString = "[{\"id\":1,\"name\":\"Irene\",\"password\":\"123456\"},{\"id\":2,\"name\":\"Aiden\","
+ "\"password\":\"123456\"}]";
List<Person> persons = JSON.parseObject(personString, new TypeToken<List<Person>>(){}.getType());
}
@Data
public static class Person {
private int id;
private String name;
private String password;
}
这个例子核心是借助TypeToken的getType()方法将期望的解析类型传递到parseObject方法中,因为TypeToken只对外提供protected的构造方法,因此,这里使用匿名内部类创建TypeToken对象。参照TypeToken结构
public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
...
protected TypeToken() {
this.runtimeType = capture();
checkState(!(runtimeType instanceof TypeVariable),
"Cannot construct a TypeToken for a type variable.\n" +
"You probably meant to call new TypeToken<%s>(getClass()) " +
"that can resolve the type variable for you.\n" +
"If you do need to create a TypeToken of a type variable, " +
"please use TypeToken.of() instead.", runtimeType);
}
protected TypeToken(Class<?> declaringClass) {
Type captured = super.capture();
if (captured instanceof Class) {
this.runtimeType = captured;
} else {
this.runtimeType = of(declaringClass).resolveType(captured).runtimeType;
}
}
public final Type getType() {
return runtimeType;
}
...
}
TypeToken的getType()方法返回改对象的实时Type类型,该类型是在构造方法中通过父类TypeCapture的capture方法获取
abstract class TypeCapture<T> {
/** Returns the captured type. */
final Type capture() {
Type superclass = getClass().getGenericSuperclass();
checkArgument(superclass instanceof ParameterizedType,
"%s isn't parameterized", superclass);
return ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
}
在capture方法中通过getClass().getGenericSuperclass()获取当前对象的直接超类Type类型,如果该超类不是参数化类型则抛出错误,如果是参数化类型,则返回参数数组中的第一个参数类型,因为TypeToken只有一个参数,因此返回的即是需被反序列化的类型。
二、Java Type简介
Type是所有类类型的父接口,它的子接口有四个:ParameterizedType、TypeVariable、GenericArrayType和WildcardType;实现类有一个:Class
- ParameterizedType
ParameterizedType 表示参数化类型,比如Collection,它有几个主要的方法:
// 返回这个Type类型的参数实际类型的组合
Type[] getActualTypeArguments();
// 返回当前ParameterizedType的原始类型
Type getRawType();
//
Type getOwnerType();
- TypeVariable
TypeVariable 表示类型变量,主要有以下几个方法:
// 得到上边界的Type数组
Type[] getBounds();
// 返回声明这个Type所在类的Type
D getGenericDeclaration();
// 返回这个TypeVariable的名称
String getName();
- GenericArrayType
GenericArrayType 表示范型数组,组成数组的元素中有范型则实现了该接口,它的组成元素是ParameterizedType 或 TypeVariable类型
// 返回组成范型数组中元素的Type类型
Type getGenericComponentType();
- WildcardType
WildcardType 是通配符类型,<?>、<? extend Number>、<? super Integer>
这些都属于WildcardType
// 得到上边界Type数组
Type[] getLowerBounds();
// 得到下边界Type数组
Type[] getUpperBounds();