In the actual work, sometimes need to dynamically obtain a class of method parameter name, the general reflection mechanism is not available, need to use the bytecode tool to get.
Package com.yanek.soa.test;
Import Java.lang.reflect.Modifier; Import Javassist.
Classpool; Import Javassist.
Ctclass; Import Javassist.
Ctmethod;
Import Javassist.bytecode.CodeAttribute;
Import Javassist.bytecode.LocalVariableAttribute;
Import Javassist.bytecode.MethodInfo; public class Methodvariablenameutil {/** * @param args */public static void main (string[] args) {string[]
Names=getmethodvariablename ("Com.yanek.soa.test.Test", "test2");
for (String name:names) {System.out.println (name); /** * Gets the parameter variable name of the method * @param classname * @param methodname * @return/public static string[] Getmetho
Dvariablename (String classname,string methodname) {try{Classpool pool = Classpool.getdefault ();
Ctclass cc = pool.get (classname);
Ctmethod cm = Cc.getdeclaredmethod (methodname);
MethodInfo MethodInfo = Cm.getmethodinfo ();
CodeAttribute CodeAttribute = Methodinfo.getcodeattribute (); String[] Paramnames = new String[cm.getparametertypes (). length];
Localvariableattribute attr = (localvariableattribute) codeattribute.getattribute (Localvariableattribute.tag);
if (attr!= null) {int pos = modifier.isstatic (Cm.getmodifiers ())? 0:1;
for (int i = 0; i < paramnames.length i++) {Paramnames[i] = Attr.variablename (i + POS);
return paramnames;
}}catch (Exception e) {System.out.println ("Getmethodvariablename fail" +e);
return null;
}
}
Package com.yanek.soa.test;
public class Test {
/**
* @param args
*
/public static void main (string[] args)
{
} String Test (String a,string b,user User) {return
"Hello";
}
public static string Test2 (String a,string b,user User) {return
"Hello";
}
public static string Test3 (String p1,string p2,user User) {return
"Hello";
}
}
Execution can get to the list of methods. Related maven dependencies:
<dependency>
<groupId>javassist</groupId>
<artifactid>javassist</ artifactid>
<version>3.12.1.GA</version>
</dependency>