Call the main method and member method of the class through class name reflection

Source: Internet
Author: User

The main method, static method, and member method without parameters of the class are called using the class name. The member methods with parameters are called. The Code is as follows:

Package com.evan.exe rcise; import java. lang. reflect. method; public class MainReflect {public static void main (String [] args) throws Exception {String className = "com.evan.exe rcise. test "; Class clazz = Class. forName (className); Method mainMethod = clazz. getMethod ("main", String []. class); Method variableMethod = clazz. getMethod ("test"); Method staticMethod = clazz. getMethod ("staticTest"); Method paraMethod = clazz. getMethod ("parameterTest", String. class, int. class); // call the main method mainMethod through reflection. invoke (null, (Object) new String [] {"evan"}); // call the parameter-free Member method variableMethod through reflection. invoke (Class. forName (className ). newInstance (); // call the static method staticMethod through reflection. invoke (clazz. newInstance (); // call the parameter member method paraMethod through reflection. invoke (clazz. newInstance (), (Object) new String ("evan"), (Object) 520) ;}} class Test {public static void main (String [] args) {for (String arg: args) {System. out. println (arg) ;}} public void test () {System. out. println ("calling common methods");} public void staticTest () {System. out. println ("called static method");} public void parameterTest (String name, int I) {System. out. println (name + I );}}


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.