package org.sxkj.common.utils;
|
|
import java.lang.reflect.Method;
|
|
public class ClassUtils {
|
/**
|
* 动态调用方法
|
*
|
* @param instance 目标对象实例
|
* @param methodName 方法名
|
* @param parameters 方法参数
|
*/
|
public static Object invokeMethod(Object instance, String methodName, Object... parameters) {
|
try {
|
// 获取参数类型数组
|
Class<?>[] parameterTypes = new Class<?>[parameters.length];
|
for (int i = 0; i < parameters.length; i++) {
|
parameterTypes[i] = parameters[i].getClass();
|
}
|
Method method = null;
|
if (parameters.length == 1 && parameters[0].toString().equals("{}")) {
|
method = instance.getClass().getMethod(methodName);
|
// 调用方法
|
Object result = method.invoke(instance);
|
System.out.println("方法调用结果: " + result);
|
return result;
|
} else {
|
// 获取方法
|
method = instance.getClass().getMethod(methodName, parameterTypes);
|
// 调用方法
|
Object result = method.invoke(instance, parameters);
|
System.out.println("方法调用结果: " + result);
|
return result;
|
}
|
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
}
|