javassist 获取方法形参的名字

普通 java 工程

注意:此方法只能用在普通工程,不能用在 web 工程,springboot 工程

import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

/**
 * 解析方法参数名称
 */

public class MethodArgumentNameResolver {

    /**
     * 获取方法的参数名称
     * @param clazz
     * @param methodName
     * @return
     */
    public static String[] handler(Class clazz,String methodName) {
        String[] ret = null;
        try {
            ClassPool pool = ClassPool.getDefault();
            pool.insertClassPath(new ClassClassPath(clazz));
            CtClass cc = pool.get(clazz.getName());
            CtMethod cm = cc.getDeclaredMethod(methodName);
            // 形参类型
            CtClass[] parameterTypes = cm.getParameterTypes();
            // 获取形参名字
            MethodInfo methodInfo = cm.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            ret = new String[parameterTypes.length];
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
            if (attr != null) {
                int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
                for (int i = 0; i < ret.length; i++) {
                    // 形参名
                    String name = attr.variableName(i + pos);
                    ret[i] = name;
                }
                return ret;
            }
        } catch (NotFoundException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

    public static void main(String[] args) {
//        String[] names = MethodArgumentNameResolver.handler("test.controller.IndexCtrl","test");
        String[] names = MethodArgumentNameResolver.handler("test.controller.RestIndexCtrl","test");
        System.out.println();
    }
}

web工程

在web工程中运行,会报错 javassist.NotFoundException

详见:
https://www.malaoshi.top/show_1IX6nXjb0Zku.html