获取方法参数名

通过spring的asm

1
2
3
4
5
6
Method[] methods = CarServiceImpl.class.getMethods();
LocalVariableTableParameterNameDiscoverer local=new LocalVariableTableParameterNameDiscoverer();
String[] params=local.getParameterNames( methods[0]);
for(String param: params){
System.out.println(param);
}

通过javassist

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Class<?> clazz = Class.forName("com.absurd.rick.service.impl.CarServiceImpl");
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get(clazz.getName());

Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method mt:declaredMethods) {
String modifier = Modifier.toString(mt.getModifiers());
Class<?> returnType = mt.getReturnType();
String name = mt.getName();
Class<?>[] parameterTypes = mt.getParameterTypes();

System.out.print("\n"+modifier+" "+returnType.getName()+" "+name+" (");


//CtMethod[] declaredMethods1 = cc.getDeclaredMethods();
CtMethod ctm = cc.getDeclaredMethod(name);
MethodInfo methodInfo = ctm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attribute = (LocalVariableAttribute)codeAttribute.getAttribute(LocalVariableAttribute.tag);
int pos = Modifier.isStatic(ctm.getModifiers()) ? 0 : 1;
for (int i=0;i<ctm.getParameterTypes().length;i++) {
System.out.print(parameterTypes[i]+" "+attribute.variableName(i+pos));
if (i<ctm.getParameterTypes().length-1) {
System.out.print(",");
}
}

System.out.print(")");

Class<?>[] exceptionTypes = mt.getExceptionTypes();
if (exceptionTypes.length>0) {
System.out.print(" throws ");
int j=0;
for (Class<?> cl:exceptionTypes) {
System.out.print(cl.getName());
if (j<exceptionTypes.length-1) {
System.out.print(",");
}
j++;
}
}
}