java method invoke

 method.invoke(b, new String[]{"a","b","c"});

尝试用java reflect 调用main.但是传递参数出现以下异常:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at test.TestReflectMain.main(TestReflectMain.java:19)

 

看了API发现:

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.


一般情况下对于参数会自动的解包为了更适合参数类型。那么传入的String[] 就会被自动解包了。

那么为了传递我们的String[]怎么不让他自动的解包呢。

两种思路:

1.欺骗:

method.invoke(null,new Object[]{(new String[]{"as","asf"})});
这样认为是Object的不再解包操作,
2.顺着他的思路重新封包一次。既然你解包我就外面再包装一次,解开不就是我要的了么。
method.invoke(null,(Object)(new String[]{"as","asf"}));

 

但是我很想知 调用的方法是如何实现的。但是看到这里我愕然了。不然我看了。不知道怎么去看。好像实现类出现了native,可能是其他语言实现了。

 

public abstract interface MethodAccessor
{
  public abstract Object invoke(Object paramObject, Object[] paramArrayOfObject)
    throws IllegalArgumentException, InvocationTargetException;
}
这个基本实现以后在研究了。解决这个问题是关键。
先记录下这个问题。这个问题在实际中可能会用到哦。用到了知道就行了。
 



 


 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值