/*************************** Function resources called during testing ****** *********************************/<br/> package COM. test. reflect; <br/> public class methodclass {<br/> Public int Mya; <br/> Public int myb; <br/> private int YY; <br/> private int MYD; </P> <p> // print a <br/> Public String printa (string instr) {<br/> Print ("The printa function starts execution! "); <Br/> Print (instr); <br/> Print (" The printa function has been executed! "); <Br/> return" this is the result of printa function execution! "; <Br/>}< br/> // print B <br/> Public void printb (string instr) {<br/> Print (instr ); <br/>}< br/> // print C <br/> Public void printc (string instr) {<br/> Print (instr ); <br/>}</P> <p> // print the function <br/> Public void print (string instr) {<br/> system. out. println (instr); <br/>}< br/>}
/****************** Test class, get all the attributes and function names of the previous class, specify a function name and print the returned result ******************************* * *****/<br/> package COM. test. reflect; <br/> Import Java. lang. reflect. field; <br/> Import Java. lang. reflect. method; <br/> public class invokemethod {<br/>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub <br/> try {<br/> class <?> Typeclass = Class. forname ("com. test. reflect. methodclass "); // Green indicates the package and class name, place the file in the Lib folder of the project <br/> // obtain the method name <br/> method [] method = typeclass. getmethods (); <br/> for (INT I = 0; I <method. length; I ++) {<br/> // use getmethods () of the class to obtain all function names <br/> system. out. println (method [I]. getname (); <br/>}< br/> // obtain the public attribute name <br/> Field [] fields = typeclass. getfields (); <br/> for (INT I = 0; I <fields. length; I ++) {<br/> system. out. println (fields [I]. getname (); <br/>}< br/> // obtain the private attribute name <br/> Field [] fields2 = typeclass. getdeclaredfields (); <br/> for (INT I = 0; I <fields2.length; I ++) {<br/> system. out. println (fields2 [I]. getname (); <br/>}< br/> // call Method for Dynamic instantiation <br/> Object object = typeclass. newinstance (); <br/> // obtain the add method (1) <br/> method addmethod = typeclass. getmethod ("printa", String. class); // parameter 1: method name <br/> // parameter 2: function acceptance parameter type <br/> // invoke of the execution Method Instance, returned results <br/> Object res = addmethod. invoke (object, "dynamically execute the printa function"); // parameter 1: instance of the class // parameter 2: input parameter of the function to be executed </P> <p> system. out. println ("the result of executing the specified function is:" + Res); <br/>} catch (exception e) {<br/> E. printstacktrace (); <br/>}< br/>}