spring 中使用反射

13 篇文章 0 订阅

通过BeanId 获取Bean 

package cn.com.kgo.eventhand.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@SuppressWarnings("static-access")
@Component
public class ContextUtil implements ApplicationContextAware {
	private static ApplicationContext commonApplicationContext;

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.commonApplicationContext = context;
	}

	/**
	 * 根据提供的bean名称得到相应的服务类
	 * 
	 * @param beanId
	 *            bean的id
	 * @return 返回bean的实例对象
	 */
	public static Object getBean(String beanId) {
		return commonApplicationContext.getBean(beanId);
	}

	/**
	 * 根据提供的bean名称得到对应于指定类型的服务类
	 * 
	 * @param beanId
	 *            bean的id
	 * @param clazz
	 *            bean的类类型
	 * @return 返回的bean类型,若类型不匹配,将抛出异常
	 */
	public static <T> T getBean(String beanId, Class<T> clazz) {

		return commonApplicationContext.getBean(beanId, clazz);
	}

}

通过反射执行Bean的方法

很多时候使用bean的时候并不能获取到实体对象和接口对象,无法对对象进行转型,这时候只能采用反射的方式执行,Bean的方法。

获取方法

Method method = ReflectUtil.getMethod(obj.getClass(), methodName);

ReflectUtil 是spring 的反射工具类 ,obj 可以是通过上面的方法获取的bean对象,getMethod方法有多个重载,可以声明参数

执行方法

第一种方式

使用java原始的方式

method.invoke(obj, args);

method 是反射获取的方法实体,obj为bean 对象,args 是参数。

第二种方式,也是推荐使用方式

使用ReflectUtil对象

ReflectionUtils.invokeMethod(method, obj, args);

method 方法实体,obj bean实体,args参数

执行成功返回object对象

 

 

 

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

keep-go-on

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值