public class Test1 {
public static void print(String[] arr){
System.out.println(String.join(" ", arr));
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
String[] arr= {"I","came","from","Laifeng","in","Hubei","Enshi,",
"which","is","a","small","developing","town"};
Class<?> c = Class.forName("com.my.test11.Test1");
Test1 test =(Test1) c.newInstance();
Method printMethod = c.getMethod("print", String[].class);
printMethod.invoke(test,(Object)arr);
}
}
以上是用反射机制调用String.join()方法完成的一个小测试
容易出错的地方是在最后一行 :printMethod.invoke(test,(Object)arr);
如果arr不强转成Object 会报错
Exception in thread “main” java.lang.IllegalArgumentException: wrong number of arguments
鼠标移至最后一行会显示如下:
Type String[] of the last argument to method invoke(Object, Object…) doesn’t exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.
翻译:
类型String []的方法调用的最后一个参数(Object,Object …)与vararg参数类型不完全匹配。 转换为Object []以确认非varargs调用,或者为varargs调用传递Object类型的各个参数。
vararg:可变参数
所以要把invoke方法的最后一个参数强转Object才行