Using reflection to call the class method, you need to use the invoke method in java.lang.reflect.Method, Object ?? Invoke (Object Object [] args), the first parameter refers to the implicitness of the method you need to call. Parameters, that is, the object belonging to that method, if the call is a static method to specify the first parameter as null, the second parameter refers to the explicit parameters of the method you want to call, because one method can have many parameters So here we must use an array to store these parameters, pay attention to this method is an array of objects. Although the valued type should be stored in, when we store the corresponding wrapper classes, this method is returned. This is an annoying problem in Java. If it is back, it is ok, we only need to convert the Object returned to the INVOKE to a specific object, but it returns a value type? We have to use it, you must first declare it, return to normal values in the method of our packaging object! Our programming is very important!
Programming basic ideas:
First get the pointer to the method that needs to be called, in fact, the pointer is not so well-understood, and Java's method pointer also has a big argument, we just call the reference! How to get a reference? You can use the CLASS class GetMethod method to return a method, then we call this reference to this reference in the invoke method using Method, it is as simple as it is, I always think that a complex concept is the most focused on using a simple example. Effective! (Under JDK1.4, pass)
Import java.lang.reflect. *;
Public class invokeMethods {public static void main (string [] args) {Employee EMP = New Employee (); /// getClass Gets the type of object to which the EMP object belongs, Class is the class /// Class is specifically used to describe Class class, such as describing a certain class, /// method, constructor, etc.! Class cl = Emp.getClass (); try {/// getMethod method The first parameter specifies a method name that needs to be called /// Here is the setage method of the Employee class, the second parameter is required to call /// method Parameter type list, is the type of parameter! If there is no parameter, you can specify null /// The method returns a method object Method Sage = Cl.getMethod ("setage", new class [] {int.class}); method Gage = Cl.getMethod ("getage", null) Method PNAME = Cl.getMethod ("PrintName", new class [] {string.class}); / ** * Using the invoke call specified method * / Object [] args1 = {new integer (25)}; // Parameter list // EMP for implicit parameters This method is not a static method must specify Sage.Invoke (EMP, ARGS1); Integer Age = (Integer) Gage.Invoke (EMP, NULL); int Age = age.intValue (); system .out.println ("THE EMPLOYEE AGE IS: AGE); Object [] args3 = {new string (" jack "}; pname.invoke (EMP, ARGS3);} catch (exception e) {E.PrintStackTrace ();} System.exit (0);}}