在項目中有時候我們會使用到反射的功能,如果使用最原始的方法來開發反射的功能的話肯能會比較復雜,需要處理一大堆異常以及訪問權限等問題。spring中提供了ReflectionUtils
這個反射的工具類,如果項目使用spring框架的話,使用這個工具可以簡化反射的開發工作。
我們的目標是根據bean的名稱、需要調用的方法名、和要傳遞的參數來調用該bean的特定方法。
下面直接上代碼:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Method; /** * Created with IntelliJ IDEA. * User: 焦一平 * Date: 2015/6/15 * Time: 18:22 * To change this template use File | Settings | File Templates. */ @Service public class ReInvokeService { @Autowired private SpringContextsUtil springContextsUtil; public void reInvoke(String beanName,String methodName,String[] params){ Method method = ReflectionUtils.findMethod(springContextsUtil.getBean(beanName).getClass(), methodName, String.class, String.class, Boolean.class,String.class); Object[] param1 = new Object[3]; param1[0]=params[0]; param1[1]=params[1]; param1[2]=true; ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param1); } }
ReflectionUtils.findMethod()方法的簽名是這樣的:
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)
依次需要傳入 class對象、方法名、參數類型
SpringContextsUtil 這個工具類實現了 ApplicationContextAware接口,可以訪問ApplicationContext的相關信息,代碼如下:
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Created with IntelliJ IDEA. * User: 焦一平 * Date: 2015/6/15 * Time: 18:36 * To change this template use File | Settings | File Templates. */ @Component public class SpringContextsUtil implements ApplicationContextAware { private ApplicationContext applicationContext; public Object getBean(String beanName) { return applicationContext.getBean(beanName); } public <T> T getBean(String beanName, Class<T> clazs) { return clazs.cast(getBean(beanName)); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }