[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 );
}
}
}