项目中反射的应用

Bertha 。 2022-04-10 13:44 294阅读 0赞

业务场景:我们时用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;

}

-———————————————————————————————————————————————————————————————————————————

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读

    相关 使用

    概述     JAVA反射机制是在运行中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态

    相关 项目应用

    业务场景:我们时用springboot做的一个app(项目模块做完后,需要加入如今日头条的推荐和关注模块) 模块:有十几个主题,主题下有若干指标,每个主题和指标都被唯一区分;