java的反射是不能獲取方法的參數名的。好比:java
[java] view plaincopyprint?spa
public String concatString(String str1,String str2){ .net
return str1+str2; code
} blog
public String concatString(String str1,String str2){ return str1+str2; }
[java] view plaincopyprint?get
public static void main(String[] args) { it
Class clazz = TestJavaAssist.class; io
try { class
ClassPool pool = ClassPool.getDefault(); exception
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(); } }