Spring框架中使用java反射无法实例化类,使用ReflectionUtils.findMethod

792 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路本文已参与「新人创作礼」活动,一起开启掘金创作之路

Spring框架中的反射问题

问题描述 在spring的框架的项目中,使用java的反射去实例化一个service类的时候获取不到该类的对象.

try {
	   Class cla = Class.forName(apiName); //数据库配置完整的包名类名
	    Object obj = cla.newInstance();//实例化这个类
	    Method[] methods = cla.getMethods();// 获得这个类的所有方法
	    // Method m = cla.getMethod(methodName); //类中的方法名
	    for(Method m:methods){ 
	          if( methodName.equals(m.getName())){
	              返回的对象类= (返回的对象类) m.invoke(obj,"1".equals(needargs) ? getAppJson : null); //调用方法 根据配置是否需要传递参数来传getAppJson或null
	          }
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error("Controller invokeMethod error!!! functionId: " + functionId + " apiName: " + apiName + " methodName: " + methodName); 
	}

使用java的反射的时候 获取的反射的service对象为空,debug的时候看见obj 为null,后续操作无法进行.

解决方案

使用spring提供的ReflectionUtils来反射service类,执行service中的方法就可以了. SpringContextUtil 这个类要implements ApplicationContextAware,里面的这几个方法是比较重要的.

public class SpringContextUtil implements ApplicationContextAware{
  private static ApplicationContext applicationContext;     //Spring应用上下文环境

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
  
    public static Object getBean(String name, Class requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }
}    

反射实现

  try {
            Object beanObj = SpringContextUtil.getBean(beanName);
            Method mh = ReflectionUtils.findMethod(beanObj.getClass(), methodName, 参数的类型.class);
            返回的对象类= (返回的对象类) ReflectionUtils.invokeMethod(mh, beanObj, "1".equals(needargs) ? getAppJson : null);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("Controller invokeMethod error!!! functionId: " + functionId + " beanName: " + beanName + " methodName: " + methodName);
            
        }

要实例化的那个service类 findMethod方法参数(类名,方法名,参数类型)

Method mh = ReflectionUtils.findMethod(beanObj.getClass(), methodName, 参数的类型.class);

这个地方不要被引导了,一开始我的参数类型写错了,报找不到方法. 参考 www.cnblogs.com/jiaoyiping/… 他里面的参数是这样的

Method method = ReflectionUtils.findMethod(springContextsUtil.getBean(beanName).getClass(), methodName, String.class, String.class, Boolean.class,String.class);

还有这种 topmanopensource.iteye.com/blog/542346

 Method method = ReflectionUtils.findMethod(convertor.getClass(), methodName, new Class[] { String.class });

这俩的参数类型不一样,根据自己的实际情况来写就行了.