吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
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
31
32
33
34
35
36
37
38
39
40
41
42
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;
    }
}