Know the class name, method name, and parameters, how to call the function, string call

Source: Internet
Author: User

Know the class name, method name, and parameters, how to call the function, string call

There are three strings: Class Name, method name, method parameter, and string. You need to call this method as follows.

1) obtain the class first.

    Class cname=null;    try {        cname = Class.forName (classname);    } catch (ClassNotFoundException e) {    e.printStackTrace();    }    

Class. forName (classname); this method is used to obtain this Class object through reflection. For details about reflection, see http://www.cnblogs.com/xiufengd/p/4723426.html, or hundreds of degrees.

2) Obtain Methods

Method [] methodes = cname. getDeclaredMethods (); for (int I = 0; I <methodes. length; I ++) {method = methodes [I]; if (method. getName (). equals (methodName) {// other operations }}

The class object obtained after reflection has a method: getDeclaredMethods (), which is used to obtain all methods declared by the class or interface. Then, cyclically traverse the obtained Method data, use the getName Method to identify the same Method as the required Method, and then obtain the Method object.

3) Call Methods

Object result=null;if(arg.equals("")){    result = method.invoke(cname,null);}else if(arg.split(",").length==1){    result = method.invoke(cname, arg);}

 

The Method object has a method called the invoke Method. This method has two parameters: the first represents the class name and the second represents the parameter. The function of this Method is to call the method Method method of the cname class, the method parameter is arg.

Current problems:

Because the arg parameter is a string, all operations can only be divided into parameter arrays in a specific method, and then multiple parameters are called.

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.