zoukankan      html  css  js  c++  java
  • 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;
        }

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

  • 相关阅读:
    csv与xlsx导出
    行业报告
    How JavaScript works: an overview of the engine, the runtime, and the call stack
    CAS单点登陆/oAuth2授权登陆
    YChaos生成混沌图像
    Why数学图像生成工具
    WHY数学图形可视化工具(开源)
    WHY翻写NEHE与红龙的3D图形程序 [开源]
    四边形密铺平面
    数学图形(1.50)三曲线
  • 原文地址:https://www.cnblogs.com/juepei/p/4086719.html
Copyright © 2011-2022 走看看