一、Java反射类库
ClassUtils.java
package com.reflect.common;
import java.lang.reflect.Method;
public class ClassUtils {
/**
* 通过类、类方法名,获取方法对应的参数信息
*
* @param obj 类实例
* @param methodName 方法名
* @return 返回值
*/
public static Class<?>[] getParameterClass(Object obj, String methodName) {
Class<?> clazz = obj.getClass();
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
/*
* 跳过非指定的方法
*/
if (!m.getName().equals(methodName)) {
continue;
}
/*
* 获取参数类型的数组,里面有参数的个数和参数的类型
*/
Class<?>[] parameters = m.getParameterTypes();
return parameters;
}
return null;
}
}
Service.java
@Service
public class Service {
private static void exec(
HttpServletRequest req, HttpServletResponse response,
String SERVER_PREFIX, String SERVER_HANDLER_CLASS) {
/*
* 2-- 根据配置的应用服务提供前缀、服务实现接口
* 通过反射机制获取请求结果
*/
String result;
// 2--1 准备参数
Class<?> clazz;
try {
// 2--2 通过反射获取对象
clazz = Class.forName(SERVER_HANDLER_CLASS);
Object impl = clazz.newInstance();
// 2--3 获取对象的方法
Class<?>[] parameters = getParameterClass(impl, PROCESS_METHOD);
Method m = clazz.getMethod(PROCESS_METHOD, parameters);
// 2--4 反射调用方法
Object[] objects = new Object[2];
objects[0] = req;
objects[1] = null;
result = (String) m.invoke(clazz.newInstance(), objects);
/*
* 3-- 封装应答
* 根据请求的Content-Type(MediaType),为HTTP响应传输对象打数据格式标签
*/
response.setContentType(MediaType.APPLICATION_XML_VALUE);
String characterEncoding = req.getCharacterEncoding();
response.setCharacterEncoding(characterEncoding);
PrintWriter printWriter = response.getWriter();
printWriter.write(result);
printWriter.flush();
} catch (ClassNotFoundException|
NoSuchMethodException|
IllegalAccessException|
InvocationTargetException |
InstantiationException|
IOException e) {
String errStr = "URL Request failed." + e.getMessage();
_logger.error(errStr);
}
}
}
二、Spring反射类库ReflectionUtils
// 2--2 通过反射获取对象
Object beanObj = SpringContextUtil.getBean(SERVER_HANDLER_CLASS);
Class<?> clazz = beanObj.getClass();
// 2--3 获取对象的方法
//Class<?>[] paramTypes = new Class[] {HttpServletRequest.class, AppParams.class, AuxParams.class};
Class<?>[] paramTypes = getParameterClass(beanObj, PROCESS_METHOD);
Method method = ReflectionUtils.findMethod(clazz, PROCESS_METHOD, paramTypes);
// 2--4 反射调用方法
Object[] objects = new Object[3];
objects[0] = req;
objects[1] = appParams;
objects[2] = null;
result = (String) ReflectionUtils.invokeMethod(method, beanObj, objects);
/*
* 3-- 封装应答
* 根据请求的Content-Type(MediaType),为HTTP响应传输对象打数据格式标签
*/
response.setContentType(MediaType.APPLICATION_XML_VALUE);
String characterEncoding = req.getCharacterEncoding();
response.setCharacterEncoding(characterEncoding);
PrintWriter printWriter = response.getWriter();
printWriter.write(result);
printWriter.flush();