反射工具类

InvokeUtils代码如下:

package com.ksource.utils;

import org.apache.commons.collections4.MultiValuedMap;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * @Author dxy
 * @Date 2024/7/16 17:54
 * @Description
 */
public class InvokeUtils {

    public static void main(String[] args) throws Exception{
        Object[] paramArr = new Object[]{"lxi",12};
        Class<?> clazz = Class.forName("com.ksource.utils.TestJava");
        Object result = invokeMethod(clazz, paramArr, "a2");
        System.out.println(result);
    }

    public static Object invokeMethod(Class clazz, Object[] paramArr, String methodName){
        try {
            MultiValuedMap<String, Class<?>[]> methodMultimap = ParamUtils.getMethodInfo(clazz.getName());
            Collection<Class<?>[]> classList = methodMultimap.get(methodName);
            Class<?>[] clazzList = null;
            for (Class<?>[] elements : classList) {
                if(paramArr.length == elements.length){
                    clazzList = elements;
                }
            }
            Method method = clazz.getMethod(methodName, clazzList);
            Object result = method.invoke(clazz.newInstance(), paramArr);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

  

posted @ 2024-07-17 16:06  岁月淡忘了谁  阅读(7)  评论(0编辑  收藏  举报