反射机制的可变参数异常解决办法

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才行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值