可变参数的方法反射可将可变参数封装成一个数组,再按照一个参数时的反射来调即可
public void add(int... nums){}的反射即可写成
Method methodAdd =类.class.getMethod("add",int[].class) ;
methodAdd.invoke(对象,new int[]{1,2,3,4,5});
下面是我测试通过的例子。楼主可试试
package gz.com;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectDemo1 {
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Demo1 demo1 = new Demo1();
demo1.add(1,2,3,4,5);
Method methodAdd = Demo1.class.getMethod("add", int[].class);
methodAdd.invoke(demo1, new int[]{1,2,3,4});
}
}
class Demo1
{
public void add(int... nums)
{
int sum = 0;
for(int i=0;i<nums.length;i++)
{
sum =sum+nums[i];
}
System.out.println(sum);
}
}
|