Java reflection String Array

Source: Internet
Author: User

[Java]
Public class Test
{
Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{

Method m = Test. class. getMethod ("wish", String. class );
M. invoke (null, new String [] {"1", "2", "3 "});
// 1. Because the method has multiple parameters, the three parameters are given in the form of arrays.
M. invoke (null, new String ("a"), new String ("B"), new String ("c "));
// 2. The array format is not required here.
}
 
Public static void wish (String str1, String str2, String str3)
{
System. out. println (str1 );
System. out. println (str2 );
System. out. println (str3 );
}
}
 
But if we want to change the parameter in the wish method to an array, how can we perform reflection? As follows:
 
Public class Test
{
Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{

Method m = Test. class. getMethod ("wish", String []. class );
// M. invoke (null, new String [] {"1", "2", "3"}); this method does not work.
// Because of the new String [] {"1", "2", "3"}, the program will regard the wish method as having three parameters of the string type, instead of taking this array as a parameter

M. invoke (null, (Object) new String [] {"1", "2", "3 "});
// 1. Forced conversion
M. invoke (null, new Object [] {new String [] {"1", "2", "3 "}});
// 2. Use the array form of the superclass, new String [] {"1", "2", "3"} as the first element of the parameter array;
// This Li shows that we can write parameters in the form of arrays.
}
 
Public static void wish (String [] strs)
{
For (String str: strs)
{
System. out. println (str );
}
}
}

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.