说明

Spring 针对反射提供的工具类 ReflectionUtils

示例

SpringContextsUtil.java

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
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;
}
}

ReInvokeService.java

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
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);
}
}