How to get method parameter names?

如何获取方法参数命名?

1.通过javassist获取

    /**
     * Get Method Parameter Names in JAVA
     * 参考:http://blog.hailinzeng.com/2014/10/10/get-method-parameter-name-in-java/
     *
     * @param clazz
     * @param method
     * @return 参数名称数组
     */
    public static String[] getMethodParamNames(Class<?> clazz, Method method) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(clazz));
        CtClass cc = pool.get(clazz.getName());
        Class<?>[] paramTypes = method.getParameterTypes();
        String[] paramTypeNames = new String[method.getParameterTypes().length];
        for (int i = 0; i < paramTypes.length; i++)
            paramTypeNames[i] = paramTypes[i].getName();
        CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));

        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
                .getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            throw new RuntimeException("class:" + clazz.getName()
                    + ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
        }

        String[] paramNames = new String[cm.getParameterTypes().length];
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < attr.tableLength(); i++) {
            map.put(attr.index(i), i);
        }
        int index = 0;
        boolean isStaticMethod = Modifier.isStatic(cm.getModifiers());
        boolean flag = false;
        for (Integer key : map.keySet()) {
            //如果是非静态方法,第0个attr.variableName(0)返回this,所以要跳过
            if (!isStaticMethod && !flag) {
                flag = true;
                continue;
            }

            if (index < paramNames.length) {
                paramNames[index++] = attr.variableName(map.get(key));
            } else {
                break;
            }
        }
        return paramNames;
    }

参考:
Get Method Parameter Names in JAVA
How to get method parameter names with javassist?
Javassist初体验

2.java8 可直接使用java.lang.reflect.Parameter#getName()获取参数命名

前提是使用javac compiler,并在编译时带上-parameters option。具体参考
Obtaining Names of Method Parameters


猜你喜欢

转载自blog.csdn.net/flysharkym/article/details/54093520