Java-使用泛型和列表的类强制转换异常

时间:2018-07-10 14:04:11

标签: java list generics

所以我试图创建一个将返回任何类型的List的方法。 这是我的方法:

    public <T> List<T> mapResponse(Response response){
    List<T> list = new ArrayList<>();
    //String responseString;

        if (response != null) {
            String responseString = response.getBody();

            if (response.getStatusCode() == 200) {
                list = objectMapper.readValue(responseString, new TypeReference<List<T>>() {
                });
            } else {
                log.error("Response status code: {} Response : {}", response.getStatusCode(), responseString);
                throw new BadRequestException(responseString);
            }
        } else {
            log.error("Response from service is null");
            throw new InternalServerErrorException(ResponseIsNull);
        }

    return list;
}

当我尝试遍历列表时,得到了java.lang.ClassCastException。

  List<Transaction> list = mapResponse(Response response);
  for (Transaction transaction : list) {
            log.info(transaction.toString()); }

我该如何解决?

谢谢!

0 个答案:

没有答案