天天看点

Java泛型与Restlet客户端

写一个与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;
    }      

这样,使用泛型,在这个封装的方法中,指定了返回数据的类型,这样就不会出现之前的错误。

除非注明转载,其他文章均为作者原创,可以自由转载,但请注明转载的本文的地址,请尊重作者的劳动成果。