Spring RestTemplate使用泛型 |
您所在的位置:网站首页 › parameterizedtypereference序列化 › Spring RestTemplate使用泛型 |
概述:Spring RestTemplate使用泛型,将Class作为泛型类型转换为ParameterizedTypeReference,以简化开发代码。但每次请求都new一个ParameterizedTypeReference对象,这点比较恶心。理想的效果是只传入一个Class对象就能确定返回值的类型,所以我们需要做的就是想办法把class对象转换为ParameterizedTypeReference对象。
RestTemplate不论是post还是get、patch都只支持传入一个class作为返回值的类型,并且不支持泛型 使用泛型需要使用exchange方法 public CommonRes post(String url,Object param,ParameterizedTypeReference reference) { return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity(param), reference).getBody(); } public void test(String url,Object param){ ParameterizedTypeReference reference = new ParameterizedTypeReference() { }; CommonRes response = post(url, param, reference); }但是使用这种方法,必须每次请求都new一个ParameterizedTypeReference对象,这点比较恶心。理想的效果是只传入一个Class对象就能确定返回值的类型,所以我们需要做的就是想办法把class对象转换为ParameterizedTypeReference对象。 转换代码如下: private ParameterizedTypeReference getReference2(Class clazz) { ParameterizedTypeImpl type = ParameterizedTypeImpl.make(CommonRes.class, new Type[]{clazz} , CommonRes.class.getDeclaringClass()); return ParameterizedTypeReference.forType(type); }另外使用jacson工具包也可以进行转换: private static final ObjectMapper objectMapper = new ObjectMapper(); private ParameterizedTypeReference getReference(Class clazz) { //objectMapper已经缓存Type,不需要额外缓存 JavaType javaType = objectMapper.getTypeFactory().constructParametrizedType(CommonRes.class, CommonRes.class, clazz); return ParameterizedTypeReference.forType(javaType); }使用上述代码优化后方法为: private ParameterizedTypeReference getReference2(Class clazz) { ParameterizedTypeImpl type = ParameterizedTypeImpl.make(CommonRes.class, new Type[]{clazz} , CommonRes.class.getDeclaringClass()); return ParameterizedTypeReference.forType(type); } public CommonRes post(String url,Object param,Class clazz) { return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity(param), getReference2(clazz)).getBody(); } public void test(String url,Object param){ CommonRes response = post(url, param, GoodsInfo.class); }看起来是不是舒服了很多,献给有需要的小伙伴们,另外Type对象获取方法比较耗资源建议进行缓存
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |