Java反射中,如果Method的参数里含有数组或者可变参数形式,那么在调用Invoke的时候,稍有点诡异,这里记录一下。可变参数实质就是数组,调用方式和普通数组一样。
用反射方式执行某个类中的main方法
- public class ReflectTest {
- public static void main(String[] args) throws Exception {
- String startingClassName=args[0];
- Method mainMethod=Class.forName(startingClassName).getMethod("main",String[].class);
- //这一点特别注意:这里使用new Object[]数组将new String[] 进行打包成一个对象
- mainMethod.invoke(null,new Object[]{new String[]{"111","222","333"}});
- }
- }
- class TestArguments {
- public static void main(String[] args)
- {
- for(String s:args)
- System.out.println(s);
- }
- }
先看一个简单的类
- public class Target {
- public void arrayInput(String[] inputs) {
- for (String each : inputs) {
- System.out.print(each);
- }
- System.out.println();
- }
- }
看如何反射调用含数组参数的方法
- import java.lang.reflect.Array;
- import java.lang.reflect.Method;
- public class ArrayReflection {
- public static void main(String[] args) {
- Class<Target> clazz = Target.class;
- try {
- Object object = clazz.newInstance();
- // 数组参数的调用方法
- Method arrayInputMethod = clazz.getMethod("arrayInput",
- String[].class);
- // 写法一,可以理解
- Object arrayObj = Array.newInstance(String.class, 2);
- Array.set(arrayObj, 0, "Hello");
- Array.set(arrayObj, 1, "World");
- arrayInputMethod.invoke(object, arrayObj);
- // 写法二,按照Eclipse提示写出来的,不理解
- String[] stringArray = new String[]{"Cafe","Baby"};
- arrayInputMethod.invoke(object, new Object[] { stringArray });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
看输出:
如果这样写
- arrayInputMethod.invoke(object, new String[]{"wrong","style"});
会报如下错误
java.lang.IllegalArgumentException: wrong number of arguments