plate和泛型类型ParameterizedTypeRefer

plate和泛型类型ParameterizedTypeRefer

本文介绍了Spring RestTemplate和泛型类型ParameterizedTypeReference集合(例如List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Abstract控制器类需要REST中的对象列表.在使用Spring RestTemplate时,它没有将其映射到必需的类,而是返回Linked HashMAp

An Abstract controller class requires List of objects from REST. While using Spring RestTemplate its not mapping it to required class instead it returns Linked HashMAp

 public List<T> restFindAll() {

    RestTemplate restTemplate = RestClient.build().restTemplate();
    ParameterizedTypeReference<List<T>>  parameterizedTypeReference = new ParameterizedTypeReference<List<T>>(){};
    String uri= BASE_URI +"/"+ getPath();

    ResponseEntity<List<T>> exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
    List<T> entities = exchange.getBody();
    // here entities are List<LinkedHashMap>
    return entities;

}

如果我使用

ParameterizedTypeReference<List<AttributeInfo>>  parameterizedTypeReference =
    new ParameterizedTypeReference<List<AttributeInfo>>(){};
    ResponseEntity<List<AttributeInfo>> exchange =
  restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);

工作正常.但是不能放入所有子类中的任何其他解决方案.

It works fine. But can not put in all subclasses, any other solution.

推荐答案

我使用以下通用方法解决了这个问题:

I worked around this using the following generic method:

public <T> List<T> exchangeAsList(String uri, ParameterizedTypeReference<List<T>> responseType) {
    return restTemplate.exchange(uri, HttpMethod.GET, null, responseType).getBody();
}

那我可以打电话给

List<MyDto> dtoList = this.exchangeAsList("http://my/url", new ParameterizedTypeReference<List<MyDto>>() {});

这确实使调用者不得不在调用时指定ParameterizedTypeReference,这意味着我不必像vels4j的答案中那样保持类型的静态映射.

This did burden my callers with having to specify the ParameterizedTypeReference when calling, but meant that I did not have to keep a static mapping of types like in vels4j's answer 

这篇关于Spring RestTemplate和泛型类型ParameterizedTypeReference集合(例如List&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:16