Method-class invoke method usage in Java reflection

Source: Internet
Author: User

Import java. Lang. Reflect. method;

Public class invoketester {

Public int add (INT param1, int param2) {return param1 + param2 ;}

Public String echo (string mesg) {return "Echo" + mesg ;}

Public static void main (string [] ARGs) throws exception {class classtype = invoketester. class; object invokertester = classtype. newinstance (); Method addmethod = classtype. getmethod ("add", new class [] {Int. class, Int. class}); // parameters received by the invoke (Object OBJ, object ARGs []) method of the method class The number must be an object. // If the parameter is of the basic type, it must be converted to an object of the corresponding packaging type. The Return Value of the invoke () method is always an object. // if the return type of the actually called method is basic data, then invoke () method will convert it to the corresponding packaging type object, // then return the object result = addmethod. invoke (invokertester, new object [] {New INTEGER (100), new INTEGER (200)}); // In jdk5.0, The binning mechanism new INTEGER (100) is enabled) it can be replaced by 100, and the system will automatically convert between int and integer. out. println (result);

method echomethod = classtype. getmethod ("Echo", new class [] {string. class}); Result = echomethod. invoke (invokertester, new object [] {"hello"}); system. out. println (result) ;}}

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.