什么是TypeReference?

时间:2025-01-23 10:28:30
//一个泛型类 @Data public class Generic<T> { private String name; private T info; } //一个普通类 @Data public class Shape { private Integer hight; private Integer wight; } //测试类 @Test public void test6() throws IOException { //创建对象并设置值 Generic<List<Shape>> generic = new Generic<>(); generic.setName("aaa"); Shape shape = new Shape(); shape.setHight(198); shape.setWight(55); Shape shape1 = new Shape(); shape1.setHight(200); shape1.setWight(58); ArrayList<Shape> list = new ArrayList<>(); list.add(shape); list.add(shape1); generic.setInfo(list); ObjectMapper objectMapper = new ObjectMapper(); //序列化 String string = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(generic); System.out.println(string); //反序列化 //使用TypeReference Generic o = objectMapper.readValue(string, new TypeReference<Generic<List<Shape>>>() { }); //不使用TypeReference // Generic o = (string, ); System.out.println(o); }