1、原理剖析
clazz = Class.forName(className);
// 手动获取spring容器的对象
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
className = toLowerCaseFirstOne(className.substring(className.lastIndexOf(".") + 1));
method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.invoke(object, parameterValues);
method.invoke(object , parameterValues);
里面的method必须是接口的实现类的方法,不是接口的方法,而且object必须是从spring容器里面拿个,千万不能new.你new就相当于和spring没有任何关系了
2、代码实现案例
/*
* 反射调用
*/
@SuppressWarnings("rawtypes")
public static Object reflectInvoke(String className, String methodName, Class[] parameterTypes,
Object[] parameterValues) {
Class<?> clazz = null;
Object object = null;
try {
clazz = Class.forName(className);
// 手动获取spring容器的对象
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
className = toLowerCaseFirstOne(className.substring(className.lastIndexOf(".") + 1));
object = wac.getBean(className);
// 原始方法:new一个对象
// object = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
clazz = object.getClass();
Method method = null;
Object result = null;
try {
method = clazz.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
try {
result = method.invoke(object, parameterValues);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
} public static String toLowerCaseFirstOne(String s) {
char[] cs = s.toCharArray();
if(cs[0]<91 && cs[0]>64)
cs[0] += 32;
return String.valueOf(cs);
}

本文介绍如何在Spring容器环境中使用反射调用指定对象的方法,并提供了一个具体的代码实现案例。该方法允许开发者通过字符串参数指定类名、方法名及参数类型等信息,从而在运行时动态地调用目标方法。
3546

被折叠的 条评论
为什么被折叠?



