2011-10-03 62 views
6

我必須動態創建一個類,但我想使用類構造函數傳遞參數。動態使用構造函數參數的Java類

目前我的代碼看起來像

Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); 
     _tempClass.getDeclaredConstructor(String.class); 
     HsaInterface hsaAdapter = _tempClass.newInstance(); 
     hsaAdapter.executeRequestTxn(txnData); 

我如何調用帶參數的構造?

回答

13

你親近,getDeclaredConstructor()返回你應該使用一個Constructor對象。此外,您需要將String對象傳遞給ConstructornewInstance()方法。

Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); 
Constructor<HsaInterface> ctor = _tempClass.getDeclaredConstructor(String.class); 
HsaInterface hsaAdapter = ctor.newInstance(aString); 
hsaAdapter.executeRequestTxn(txnData); 
1
Constructor constructor = _tempClass.getDeclaredConstructor(String.class); 
Object obj = constructor.newInstance("some string"); 
6
Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); 

// Gets the constructor instance and turns on the accessible flag 
Constructor ctor = _tempClass.getDeclaredConstructor(String.class); 
ctor.setAccessible(true); 

// Appends constructor parameters 
HsaInterface hsaAdapter = ctor.newInstance("parameter"); 

hsaAdapter.executeRequestTxn(txnData);