posts - 145,comments - 23,views - 73万

在项目中有时候我们会使用到反射的功能,如果使用最原始的方法来开发反射的功能的话肯能会比较复杂,需要处理一大堆异常以及访问权限等问题。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;
    }
}
复制代码

 



 

posted on   梦中彩虹  阅读(31805)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示