1. 程式人生 > >Spring框架中使用java反射無法例項化類,使用ReflectionUtils.findMethod

Spring框架中使用java反射無法例項化類,使用ReflectionUtils.findMethod

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);
Method method = ReflectionUtils.findMethod(springContextsUtil.getBean(beanName).getClass(), methodName, String.class, String.class, Boolean.class,String.class);
 Method method = ReflectionUtils.findMethod(convertor.getClass(), methodName, new Class[] { String.class });

這倆的引數型別不一樣,根據自己的實際情況來寫就行了.