Anatomy of Java Reflection Main method

Source: Internet
Author: User

The previous article reflected the member method of the class, and the main method should also be included, because the main method is a static method.

But the actual Mian reflection is slightly different, the reason is mainly to maintain 1.5 compatible 1.4 version during the upgrade process: reasoning as follows

1. The parameter of the main method is a parameter of type string[]

2, 1.5 support variable parameters, so it can be variable parameter form to read the parameters,

such as: Main (string[]{"Arg1", "Arg2"}) ===>

Main ("Arg1", "arg2")

3, but in 1.4, does not support variable parameters, so will not be decomposed, directly as the main (string[]{"Arg1", "AREG2"})

4, for compatibility with 1.4 version, the main method is still only receive a parameter type string[] parameter

Combine the above:

When you pass in the string["arg0", "arg1", the 1.5 version will be resolved to: Two parameter values are "arg0", "arg1" parameters

A parameter that only receives a string[] type with the main method does not conform.

There are two ways to handle this:

1. Pass in an array and put string[] in the array: New object[]{new string[]{"Arg1", "Arg2"}}

2. Convert an array to an object

The test generation file is as follows:

Mian Method:

1  Package Cn.rt.gwq; 2 3  Public class maintest {4     5      Public Static void Main (string[] args) {6         System.out.println ("Main run ..."); 7     }89 }

Demo test Method:

1  PackageCn.rt.gwq;2 3 ImportJava.lang.reflect.Method;4 5  Public classDemo_mainrflt {6 7      Public voidTest ()throwsexception{8         9Class clazz = Class.forName ("Cn.rt.gwq.mainTest");Tenmethod = Clazz.getmethod ("main", string[].class); One         //method One: Put an array inside the array AMethod.invoke (NULL,Newobject[]{Newstring[]{"arg0", "Arg1"}}); -         //method Two: Cast the array into object -Method.invoke (NULL, (Object)Newobject[]{"arg0", "Arg1"}); the          -     } -      -}

Anatomy of Java Reflection Main method

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.