I have to create a class dynamically but I want to use class constructor passing parameter.
Currently my code looks like
Class<HsaInterface> _tempC开发者_如何学Class = (Class<HsaInterface>) Class.forName(hsaClass);
_tempClass.getDeclaredConstructor(String.class);
HsaInterface hsaAdapter = _tempClass.newInstance();
hsaAdapter.executeRequestTxn(txnData);
How can I call the constructor with the parameter ?
You got close, getDeclaredConstructor()
returns a Constructor
object you're supposed to be using. Also, you need to pass a String
object to the newInstance()
method of that Constructor
.
Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass);
Constructor<HsaInterface> ctor = _tempClass.getDeclaredConstructor(String.class);
HsaInterface hsaAdapter = ctor.newInstance(aString);
hsaAdapter.executeRequestTxn(txnData);
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);
Constructor constructor = _tempClass.getDeclaredConstructor(String.class);
Object obj = constructor.newInstance("some string");
精彩评论