什么是TypeReference
TypeReference是表示泛型的引用,主要提供了一种获取泛型参数的类型信息,对泛型的反序列化场景会用到TypeReference。
使用
package zdy.com;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* @author zdy
*/
public class TypeReference{
public static void main(String[] args) {
testTypeReference();
}
static void testTypeReference() {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(9);
list.add(4);
list.add(8);
JSONObject jsonObj = new JSONObject();
jsonObj.put("zdy", list);
System.out.println(jsonObj);
// 之前取值
String o = jsonObj.getString("zdy");
List<Integer> list1 = JSON.parseArray(o, Integer.class);
System.out.println(list1);
// 使用TypeReference
List<Integer> list2 = jsonObj.getObject("zdy", new TypeReference<List<Integer>>(){});
System.out.println(list2);
}
}
解释:
TypeReference是Java泛型和反射结合的一个类。它用于在运行的时候提供泛型的具体信息,我们上面 new TypeReference<List<Integer>>(){}创建了Typereference的匿名子类,并指定了泛型类型是List<Integer>,这样,当getObject方法返回数据的时候,他就会知道返回的是一个list<Integer>类型的数据。