2015-11-11 29 views
0

我使用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類型的對象列表。這裏真的發生了什麼?

回答

0

在這個例子中,你只是將它轉換爲一個通用列表。鑄造到List<String>應該給你「所需」的錯誤。

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

這會在編譯時給我一個錯誤。但是,在我的帖子中顯示的代碼在將'List '轉換爲'List '時應該會產生運行時錯誤。不是嗎? –

+0

在這種情況下,您再次將它轉換爲泛型列表,而不會嘗試匹配此行中的類型。如果您嘗試訪問列表「用戶」中的對象,將會得到ClassCastException。 – Lukehey

0

由於您正在轉換爲List,因此您會收到此行爲。

WHE的JVM執行

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

的JVM僅指向的用戶變量的內存空間。如果你想得到ClassCastException你必須使用列表的任何值。例如:

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