java封装返回结果应用 利用反射机制

//此方法是自己琢磨的,可能有漏洞--符合我的系统目前的需求,大家可以借鉴
public ResponseMessage exec (String funname, Object[] params,Object service)-----方法名称,参数,接口
{
ResponseMessage result = new ResponseMessage();
try
{
Object t;
Method m;
if(params.length>0){//有参数
Class<?>[] paramclass= new Class<?>[params.length];
for(int i=0;i<params.length;i++){
if(funname.equals("bbb") && params[i]==null){-------------此处是有一些特殊的方法,有的参数是null(判断不出来类型,则手动给一下)
paramclass[i]=new String[]{}.getClass();
}else {
paramclass[i] = params[i].getClass();
}
}
m = service.getClass().getMethod(funname, paramclass);//获取方法
t =m.invoke(service, params);//装载
}else{//无参数
m = service.getClass().getMethod(funname);//获取方法
t =m.invoke(service);//装载
}
return result.newOkInstance(t);//执行
}
catch (InvocationTargetException e){//遇到了获取不到错误信息的情况,最终下面的方式是可以的
Throwable t = e.getTargetException();// 获取目标异常
String em=t.getMessage();
return result.newErrorInstance(t.getMessage());
}catch (Exception e){
return result.newErrorInstance(e,e.getMessage());
}
}


应用例子
public ResponseMessage updateDetailData(@RequestBody ExtDetail extdetail) {
return this.exec("updateDetailData",new Object[]{extdetail},service);
}
 

猜你喜欢

转载自www.cnblogs.com/sky-zky/p/11736896.html