1 Packagereflecttest;2 3 ImportJava.lang.reflect.Method;4 5 /**6 * By getting the class type, and then getting the method object, the methods of the class are called ,7 * and calling methods directly through class objects can achieve the same effect, where the example calls the three methods of the object8 * @authorWang9 *Ten */ One Public classMethodDemo1 { A Public Static voidMain (string[] args) { - - //1. To get a method is to get the information of the class, get the class information first to get the class type, to get the print (int, int) method theA A1 =NewA (); -Class C =A1.getclass (); - - //2. Get the method name and the parameter list to determine how GetMethod gets the public method Getdelcaredmethod its own declared method + Try { -System.out.println ("================== call print (int a, int b) method"); + //Method m = C.getmethod ("Print", New Class[]{int.class,int.class}); AMethod m = C.getmethod ("Print",int.class,int.class); at //reflection operation of the method - //A1.print (10, 20); The reflection operation of a method is exactly the same as the effect of a method call and a A1.print call with an M object - //method returns a specific return value if no return value is returned for null - //Object o = M.invoke (a1,new object[]{10,20}); -Object o = m.invoke (A1, 10, 20); - in -System.out.println ("================== call Print (string A, String B) method"); to + - //Get method Print (string,string) theMethod m1 = C.getmethod ("Print", String.class, String.class); * //using methods for reflection operations $ //a1.print ("Hello", "World");Panax Notoginsengo = m1.invoke (A1, "Hello", "World"); - the +SYSTEM.OUT.PRINTLN ("=================== calls the Print method without parameters"); A the + //Method m2 = C.getmethod ("Print", New class[]{}); -Method m2 = C.getmethod ("Print"); $ //M2.invoke (A1, New object[]{}); $ M2.invoke (A1); - - the}Catch(Exception e) { - //TODO auto-generated Catch blockWuyi e.printstacktrace (); the } - Wu } - } About $ classA { - Public voidprint () { -System.out.println ("HelloWorld"); - } A + Public voidPrintintAintb) { theSystem.out.println (A +b); - } $ the Public voidPrint (String A, string b) { theSystem.out.println (A.touppercase () + "," +b.tolowercase ()); the } the}
Calling methods in Java by method object