Text here, the example given is related to how to obtain information about the class. We can also use reflection to do something else, such as executing a method that specifies a name. The following example illustrates this action:
Import java.lang.reflect.*;PublicClass Method2 {PublicIntAddint A,int b) {return a + B; }PublicStaticvoidMain (String args[]) {try {Class cls = Class.forName ("Method2"); Class partypes[] =new class[2]; Partypes[0] = Integer.type; Partypes[1] = Integer.type; Method meth = Cls.getmethod ( New Method2 (); Object arglist[] = new object[2]; arglist[ 0] = new Integer (37); Arglist[1] = new Integer (47); Object retobj = Meth.invoke (Methobj, arglist); Integer retval = (integer) retobj; System. out.println (Retval.intvalue ());} catch (Throwable e) {System.err.println (e);}}
If a program is executing somewhere and knows that a method needs to be executed, the name of the method is specified during the run of the program (for example, in the JavaBean development environment), then the program above demonstrates how to do it.
In the example above, GetMethod is used to find a method named Add with two integer parameters. After the method is found and the corresponding method object is created, it is executed in the correct object instance. When you execute this method, you need to provide a list of parameters, which in the above example wraps two integer objects of integers 37 and 47, respectively. The return of the execution method is also an integer object that encapsulates the return value of 84.
To execute a method based on the name of the method