我是靠谱客的博主 体贴豌豆,这篇文章主要介绍项目中反射的应用,现在分享给大家,希望可以做个参考。

业务场景:我们时用springboot做的一个app(项目模块做完后,需要加入如今日头条的推荐和关注模块)

模块:有十几个主题,主题下有若干指标,每个主题和指标都被唯一区分;

架构:有一个总接口,抽取主题相同的方法;每个主题分别实现这个总接口

(因为安全问题,项目代码无法拷贝,纯手敲)

核心代码:

//通过反射获得接口对应的实现类

//param.getCode就是指标code,由指标获得对应的主题(在数据库中查找);再由主题获得对应的实现类,上面说了每个主题分别实现了这个总接口;主题怎么获得对应的实现类?写一个枚举类,把主题code和实体类名对应(配置1)

//具体看分割线下面

IndicatorDetatilService   detailService =AppContext.determineServiceByIndCode(param.getCode);

//通过charType获得方法名

//methodName是数据库中的配置获得,指标code对应方法(配置2)

//然后又是一个枚举类,methodName对应具体方法(配置3)

String  methodName = IndChartMethodEnum.getMethodByIndcode(methodName);

//通过反射获得结果

//detailService:具体实体类;methodName:方法名;new Object[] {param} 方法参数;IndRequestParam.class:参数的class

//具体看第二个分割线下面

Object result =Utils.executeReflectMethode(detailService,methodName,new Object[]{param},IndRequestParam.class)

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------

AppContext中的方法:

public static IndicatorDetailService detemineServiceByIndCode(String code){

IndicatorService indicatorService =applicationContext.getBean("indicatorService",IndicatorService.class);

String topicCode =indicatorService.getTopicCodeByIndCode(code);

return null !=applicationContext?

//上面说的(配置1)

applicationContext.getBean(TopicEnum.getServiceNameByTopicCode(topicCode),IndicatorDetailServece.class):null;

}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Utils中的executeReflectMethode

public static Object executeReflectMethode(Object bean,String methodName,Object[] params,Class<?>... paramClass){

Method serviceMethod =null;

if(null == paramClass || 0==paramClass.length){

serviceMethod =bean.getClass().getMethod(methodName);

}else{

serviceMethod =bean.getClass().getMethod(methodName,paramClass);

}

Object result =serviceMethod.invoke(bean,params);

return result;

}

-------------------------------------------------------------------------------------------------------------------------------------------------------

 

最后

以上就是体贴豌豆最近收集整理的关于项目中反射的应用的全部内容,更多相关项目中反射内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(123)

评论列表共有 0 条评论

立即
投稿
返回
顶部