java的反射是不能获取方法的参数名的。比如:
[java] view plaincopyprint?
public String concatString(String str1,String str2){
return str1+str2;
}
public String concatString(String str1,String str2){ return str1+str2; }
[java] view plaincopyprint?
public static void main(String[] args) {
Class clazz = TestJavaAssist.class;
try {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get(clazz.getName());
CtMethod cm = cc.getDeclaredMethod("concatString");
// 使用javaassist的反射方法获取方法的参数名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
// exception
}
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++)
paramNames[i] = attr.variableName(i + pos);
// paramNames即参数名
for (int i = 0; i < paramNames.length; i++) {
System.out.println(paramNames[i]);
}
} catch (NotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) { Class clazz = TestJavaAssist.class; try { ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get(clazz.getName()); CtMethod cm = cc.getDeclaredMethod("concatString"); // 使用javaassist的反射方法获取方法的参数名 MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag); if (attr == null) { // exception } String[] paramNames = new String[cm.getParameterTypes().length]; int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < paramNames.length; i++) paramNames[i] = attr.variableName(i + pos); // paramNames即参数名 for (int i = 0; i < paramNames.length; i++) { System.out.println(paramNames[i]); } } catch (NotFoundException e) { e.printStackTrace(); } }
javassist:增强型的java反射工具,获取方法参数名
原文:http://my.oschina.net/sniperLi/blog/492057