Java泛型Restletclient

写一个与restletserver通信的client类。用于測试通信是否成功。而且进行交互。为了方便其它人使用。于是,写一个通用的方法封装起来,但是中途却放生了一些问题。

依照正常写法,顺序走下来是这种:

复制代码
 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();
        }
    }
复制代码

这样没什么问题。能够成功拿到server返回的数据。于是在这个基础上把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;
    }
复制代码

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

除非注明转载,其它文章均为作者原创,能够自由转载。但请注明转载的本文的地址。请尊重作者的劳动成果。
分类:  webservices
标签:  restlet
1
0
(请您对文章做出评价)
« 上一篇: 使用回调方式写POI导入excel工具类
posted @  2014-11-10 11:04  薛定谔的猫_ 阅读( 305) 评论( 0编辑  收藏

转载于:https://www.cnblogs.com/blfshiye/p/4803033.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值