wrong number of arguments,java方法反射時數組參數的坑


java方法中只有一個參數是數組,反射的時候我們不能想當然的傳歌數組進去,傳數組進去的時候表示多個參數。
兩個數組不是一個意思啊。
我們應該把數組轉為objet,這樣才表示一個參數。

import java.lang.reflect.Method;

public class MethodTest {
	public void a(String[] args) {
		System.out.println("a");
	}

	public static void main(String[] args) throws Exception {
		MethodTest obj = new MethodTest();
		Method m = obj.getClass().getMethod("a", String[].class);

		m.invoke(obj, new String[1]);  // new String[1] 其實是null,是一個object
		m.invoke(obj, (Object) new String[] {}); // 這里強制轉成了object,所以也是object
		m.invoke(obj, new String[] {}); // 報錯,這里是個數組,是個object數組,a方法只有一個參數,所以報錯

	}
}



結果是
a
a
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:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM