寫一個與restlet伺服器通信的用戶端類,用于測試通信是否成功,并且進行互動。為了友善其他人使用,于是,寫一個通用的方法封裝起來,可是中途卻放生了一些問題。
按照正常寫法,順序走下來是這樣的:
public static void main(String args[]){
String url="http://localhost:8888/hi";
ClientResource clientResource=new ClientResource(url);
User user=new User();
user.setName("zz");
user.setAge("12");
Representation representation=clientResource.post((new JacksonRepresentation<User>(user)));
JacksonRepresentation<User> jacksonRepresentation=new JacksonRepresentation<User>(representation,User.class);
try {
User user1=jacksonRepresentation.getObject();
System.out.println(user1.getName());
System.out.println(user1.getAge());
} catch (IOException e) {
e.printStackTrace();
}
}
這樣沒什麼問題,可以成功拿到伺服器傳回的資料,于是在這個基礎上把restlet的東西包裝起來。這樣寫的:
public static Object getServerResponse(String url,Object user){
ClientResource clientResource=new ClientResource(url);
Representation representation=clientResource.post((new JacksonRepresentation<Object>(user)));
JacksonRepresentation<Object> jacksonRepresentation=new JacksonRepresentation<Object>(representation,Object.class);
Object o=null;
try {
o=jacksonRepresentation.getObject();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
這樣在main方法中,把object轉換為User就可以了。但是轉換過程中,會報一個錯誤:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to test.User
無法将LinkedHashMap轉換為User,代碼中并沒有用到LinkedHashMap,應該是restlet轉換過程中才發生的這個問題。後來糾結了半天,問了一下比較有經驗的同僚,才知道上面的轉換,并沒有給傳回的類型明确的定義,隻轉換為object,這樣是不可以的。
經過改造,最後寫法是這樣的:
public static<T, V> V get(String url, T data, Class<V> response) {
ClientResource clientResource=new ClientResource(url);
Representation representation=clientResource.post((new JacksonRepresentation<T>(data)));
JacksonRepresentation<V> jacksonRepresentation=new JacksonRepresentation<V>(representation, response);
try {
return jacksonRepresentation.getObject();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
這樣,使用泛型,在這個封裝的方法中,指定了傳回資料的類型,這樣就不會出現之前的錯誤。
除非注明轉載,其他文章均為作者原創,可以自由轉載,但請注明轉載的本文的位址,請尊重作者的勞動成果。