利用javassist获取java的方法参数名

import java.lang.reflect.Method;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

public class MethodUtil {

    public static String[] getAllParamaterName(Method method)
	    throws NotFoundException {
	Class<?> clazz = method.getDeclaringClass();
	ClassPool pool = ClassPool.getDefault();
	CtClass clz = pool.get(clazz.getName());
	CtClass[] params = new CtClass[method.getParameterTypes().length];
	for (int i = 0; i < method.getParameterTypes().length; i++) {
	    params[i] = pool.getCtClass(method.getParameterTypes()[i].getName());
	}
	CtMethod cm = clz.getDeclaredMethod(method.getName(), params);
	MethodInfo methodInfo = cm.getMethodInfo();
	CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
	LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
		.getAttribute(LocalVariableAttribute.tag);
	int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
	String[] paramNames = new String[cm.getParameterTypes().length];
	for (int i = 0; i < paramNames.length; i++) {
	    paramNames[i] = attr.variableName(i + pos);
	}
	return paramNames;
    }

}





测试类:
import static org.junit.Assert.assertArrayEquals;
import java.lang.reflect.Method;
import org.junit.Test;

public class MethodUtilTest {
    @Test
    public void methodTest() throws Exception {
	Method method = A.class.getMethod("test", String.class);
	String[] paramaterName = MethodUtil.getAllParamaterName(method);
	assertArrayEquals(paramaterName, new String[] { "name" });
    }

}



测试用到的例子类
public class A {
    
    public String test(String name) {
	return name;
    }

}


你可能感兴趣的:(javassist)