java 反射机制应用


public class BaseController {

/**
* 通过指定的bean处理业务,非核心流程,不能支持java 动态代理对象@transactional注解的类
* @param bean
* @throws Throwable
*/
@SuppressWarnings("unchecked")
protected void process(BeanBase bean) throws Throwable {
bean.setDatas(Util.converToBean(bean));
String processorName = bean.getNeedcontrolprocess();
if(processorName == null || processorName == ""){
return;
}
String[] beanAndMethod = processorName.split("\\.");
String beanName = beanAndMethod[0];
//Service层里的方法名
String methodName = "process";
if(beanAndMethod.length > 1){
methodName = beanAndMethod[1];
}
//spring 反射获得Service层的服务类beanName=taxFavInfo(@Service("taxFavInfo"))
Object processBean = ApplicationContextHepler
.getBeanByName(beanName);
if (processBean == null) {
throw new ServiceException("数据格式非法,没有找到相应的流程!");
}
bean.setDatas(Util.converToBean(bean));
//获得运行时Class实例
@SuppressWarnings("rawtypes")
Class clazz = processBean.getClass();
@SuppressWarnings("rawtypes")
Class cz[] = new Class[1];
cz[0] = BeanBase.class;

Method method = null;
try {
//Service层里的methodName(BeanBase bean)参数是BeanBase类型。
method = clazz.getDeclaredMethod(methodName,cz);
//反射机制调用方法 参数1:service里的全路径,参数2:methodName方法的参数
method.invoke(processBean,bean);
bean.setContent(Util.converToStr(bean));
} catch (NoSuchMethodException e) {
throw new ServiceException("没找到相应的处理方法!");
} catch (SecurityException e) {
throw new ServiceException("安全检查不通过!");
} catch (IllegalAccessException e) {
throw new ServiceException("非法访问!");
} catch (IllegalArgumentException e) {
throw new ServiceException("参数不合法!");
} catch (InvocationTargetException e) {
if(e.getTargetException() != null){
if(e.getTargetException() instanceof ServiceException){
throw (ServiceException)e.getTargetException();
}else{
throw e.getTargetException();
}
}else{
throw new ServiceException("调用失败"+e.getMessage());
}
}
}

/**
* 获取创建者工号字符串
* 方法说明:<br>
*
* @return
*/
protected String getCreateId() {
return "|createId:"+UserUtil.getCurrentUser().getEmpCode();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值