Java reflection is not able to get the parameter name of the method. Like what:
[Java] view Plaincopyprint?
-
Public String concatstring (String str1,string str2) {
-
return str1+str2;
-
}
public string concatstring (string str1,string str2) {return str1+str2; }
to get the parameter name "STR1", and "str1", it is not possible to use the reflection from the JDK. But we use third-party packagesJavaassistcan be obtained.
[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");
-
-
//Use Javaassist's reflection method to get the parameter name of the method
-
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 is the name of the parameter
-
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");// gets the parameter name of the method using the Javaassist reflection method 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 is the parameter name for (int i = 0; i < paramnames.length; i++) {System.out.println ( Paramnames[i]);}} catch (notfoundexception e) {e.printstacktrace ();}}
Javassist: Enhanced Java Reflection tool to get method parameter names