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;
}
這個基本實現以後在研究了。解決這個問題是關鍵。
先記錄下這個問題。這個問題在實際中可能會用到哦。用到了知道就行了。
 



 


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章