2015-05-12 55 views
0

我正在學習Java中的Reflection,並嘗試構造一個Constructor的例子。但是有一個問題:「錯誤的參數」。 通過谷歌和stackoverflow搜索,我找不到我目前面臨的同樣的問題。 任何人都可以請幫我理解這個問題,非常感謝。 這是我的代碼:反射newinstance構造函數java錯誤參數的數量

public static void main(String[] args) { 
    PrintClass f = new PrintClass(); 
    Class cl = f.getClass(); 
    Constructor<?> constructor[] = cl.getDeclaredConstructors(); // cl.getDeclaredConstructors() also won't work... 

    f.field1 = 3; 
    PrintClass p1 = null; 
    PrintClass p2 = null; 

    try { 
     p1 = (PrintClass) constructor[0].newInstance(); // constructor[0].newInstance((Object[])args) also won't work... 
     p2 = (PrintClass) constructor[1].newInstance("this is not PrintClass-------"); 

     p1.print(); 
     p2.print(); 

    } catch (InstantiationException | IllegalAccessException 
      | IllegalArgumentException | InvocationTargetException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    } 
} 

class PrintClass { 
String s = "this is PrintClass..."; 
int field1; 

public PrintClass(String s) { 
    this.s = s; 
} 

public PrintClass() { 
} 

public void print() { 
    System.out.println(s); 
} 

}

,這是錯誤

java.lang.IllegalArgumentException: wrong number of arguments 
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
at java.lang.reflect.Constructor.newInstance(Unknown Source) 
at reflection.MainClass.main(MainClass.java:18) 

再次感謝你這麼多幫助我理解這個問題。 :)

回答

2

你打電話的第一個沒有參數的兩個構造函數。但你怎麼能確信數組中的第一個構造函數是沒有參數的構造函數,而不是期望String的那個?

你不能,因爲the javadoc說:

返回的數組中的元素沒有排序,並且不以任何特定的順序。

如果你想在類的無參數的構造函數的引用,你應該叫

cl.getDeclaredConstructor(); 

如果要構造以一個字符串作爲參數的引用,你應該叫

cl.getDeclaredConstructor(String.class); 
+0

哇,改變你的建議後,我的超級天才計劃現在工作正常。 JB Nizet:謝謝你,你是一個天才。 ! – zoro

+1

@ zoro謝謝你,但我不是天才。只是一位經驗豐富的開發人員,他知道大多數編程問題可以通過閱讀文檔來解決:) –