我使用Spring開發REST Web服務。下面的第一個代碼是我的Web服務的一個方法,它返回一個用戶列表。第二個代碼是我的Spring REST模板客戶端從該Web服務方法獲取響應。Spring REST模板中奇怪的Casting行爲
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
類型的對象列表。這裏真的發生了什麼?
這會在編譯時給我一個錯誤。但是,在我的帖子中顯示的代碼在將'List'轉換爲'List '時應該會產生運行時錯誤。不是嗎? –
在這種情況下,您再次將它轉換爲泛型列表,而不會嘗試匹配此行中的類型。如果您嘗試訪問列表「用戶」中的對象,將會得到ClassCastException。 – Lukehey