Spring REST模板中的奇怪转换行为

时间:2015-11-11 15:44:27

标签: spring rest casting resttemplate

我正在使用Spring开发REST Web服务。下面的第一个代码是我的Web服务的方法,它返回用户列表。第二个代码是我的Spring REST Template客户端从该Web服务方法获取响应。

获取用户列表的Web服务方法:

@RequestMapping(value = "/allusers", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getAllUsers() {

    List<UserDetails> users = userServices.getAllUsers();
    HttpHeaders header = new HttpHeaders();
    header.setExpires(600);
    HttpEntity<List<UserDetails>> httpEntity = new HttpEntity<>(users, header);
    HttpStatus httpStatus;
    if(users != null){
        httpStatus = HttpStatus.OK;
    } else {
        httpStatus = HttpStatus.NOT_FOUND;
    }

    return new ResponseEntity<>(httpEntity, httpStatus);
}

REST客户端

@RequestMapping("/list_all_users")
public ModelAndView goAllUsers() {
    ModelAndView mv = new ModelAndView("allusersdisplay");
    String url = "http://localhost:8080/SpringRestAddrs/services/allusers";
    RestTemplate rTemplate = new RestTemplate();
    *List<String> users = (List)rTemplate.getForObject(url, HttpEntity.class).getBody();*
    mv.addObject("users", users);
    return mv;
}

由于ClassCastException对象的主体包含HttpEntity类型的对象列表,而UserDetails List,我希望该行周围的String被星号(*)包围左侧定义的是ratingnumber类型的对象列表。这里真的发生了什么?

2 个答案:

答案 0 :(得分:0)

在此示例中,您只是将其强制转换为通用列表。投射到bin\File.extension 会给你“所需”的错误。

List<String>

答案 1 :(得分:0)

您正在获取此行为,因为您正在转换为List。

JVM执行

List<String> users = (List)rTemplate.getForObject(url, HttpEntity.class).getBody();

JVM仅将users变量指向该内存空间。如果要获取 ClassCastException ,则必须使用List的任何值。例如:

System.out.println(users.get(0));