反射机制 Class.getDeclaredMethod

public static Response call(Object obj,Request req){
    Class cls = obj.getClass();
    Response res=new Response();
    try{
        //method根据请求的方法,和参数类型断定是调用了那个方法
        Method method=cls.getDeclaredMethod(req.getMethod(),req.getParamTypes());
        //调用方法,传入具体要执行的类或对象,执行这个对象或类里面的 method 方法,得到的返回值
        Object object = method.invok(obj,req.getparam());
        res.setValue(obj);
        return res;
    }catch(InvocationTargetException e){
        //方法执行异常
        Exception ex = (Exception) e.getTargetException();
        res.setException(ex);
        return res;
    }catch(Exception e){
        e.printStackTrace();
        res.setException(e);
        return res;
    }

    //测试

public static void main(String[] args){
    Request req = new Request("charAt",new Class[]{int.class},new Object[]{2});
    Response res = Utils.call("addfdcsfdd", req);
    System.out.println(res.getValue());  //得到 d

    ///
    ExamService examServ = new ExamServiceImpl();
    Config config = new Config("client.properties");
    EntityContext entityContext = new EntityContext(config);
    examServ.setEntityContext(entityContext);
     //精确找到请求的 login 方法
    req = new Request("login",new Class[]{int.class,String.class},new Object[]{1001,"1234"}); 
    //发出req请求,执行examServ接口的login方法 
    res = Utils.call(examServ,req);
    System.out.println(res.getValue()); //得到 id号为1001的名字
  }
}

转载于:https://www.cnblogs.com/WIT-Evan/archive/2013/05/17/7291435.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值