java method invoke

来源:互联网 发布:it makes sense to 编辑:程序博客网 时间:2024/05/20 18:18
 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;}
这个基本实现以后在研究了。解决这个问题是关键。
先记录下这个问题。这个问题在实际中可能会用到哦。用到了知道就行了。
 



 


 

 

 

原创粉丝点击