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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章