一. 思路
1.通过反射找到对应的方法名;
2.通过参数个数确定要调用的方法;
3.通过参数类型转换输入参数的类型;
4.通过Method.invoke方式执行。
二.代码如下:
public Map<String, Object> invoke(String methodName, String param) {
Map<String, Object> res = Maps.newHashMap();
methodName = methodName.trim();
param = param.trim();
if (StringUtils.isBlank(methodName)) {
res.put("msg", "请输入方法");
return res;
}
Jedis jedis = null;
try {
jedis = pool.getResource();
String[] params = null;
Method target = null;
Object[] targetParams;
if (StringUtils.isNotBlank(param)) {
params = param.split(" ");
targetParams = new Object[params.length];
} else {
targetParams = new Object[]{};
}
// 遍历找到同名方法
List<Method> methods = Lists.newArrayList();
for (Class<?> searchType = jedis.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
Method[] methodArray = searchType.getDeclaredMethods();
for (Method method : methodArray) {
if (method.getName().equals(methodName)) {
Reflections.makeAccessible(method);
methods.add(method);
}
}
}
// 根据参数个数判断正确方法
for (Method method : methods) {
logger.error(method.getName());
Class<?>[] parameterTypes = method.getParameterTypes();
if (ArrayUtils.isNotEmpty(parameterTypes) && ArrayUtils.isNotEmpty(params)) {
logger.error(parameterTypes[0].getName());
if ("[B".equals(parameterTypes[0].getName())) {
continue;
}
if (parameterTypes.length == params.length) {
target = method;
break;
}
} else if (ArrayUtils.isEmpty(params) && ArrayUtils.isEmpty(parameterTypes)) {
target = method;
break;
}
}
// 根据Method参数转换输入参数数据类型
if (null != target && ArrayUtils.isNotEmpty(params)) {
Class<?>[] parameterTypes = target.getParameterTypes();
for (int i = 0; i < params.length; i++) {
if (parameterTypes[i].getName().contains("String")) {
targetParams[i] = params[i];
} else if (parameterTypes[i].getName().contains("int")) {
targetParams[i] = Integer.valueOf(params[i]);
} else if (parameterTypes[i].getName().contains("double")) {
targetParams[i] = Double.valueOf(params[i]);
} else if (parameterTypes[i].getName().contains("float")) {
targetParams[i] = Float.valueOf(params[i]);
}
}
}
Object result = target.invoke(jedis, targetParams);
res.put("msg", jsonMapper.toJson(result));
} catch (Exception e) {
logger.error("执行Redis异常", e);
res.put("msg", e);
} finally {
if (jedis != null) {
jedis.disconnect();
}
}
return res;
}