Class.forName("className").newInstance()
總是調用沒有參數的默認構造函數。
要調用,而不是無參數無參數的構造函數參數化的構造,
- 你必須傳遞類型
Class[]
得到Constructor
與參數類型的Class
getDeclaredConstructor
方法你必須創建構造函數實例通過傳遞值Object[]
爲
newInstance
方法Constructor
示例代碼:
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection(String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor(new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
輸出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow