To execute a method based on the name of the method

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.