Java class dynamically with the Constructor parameter

I need to create a class dynamically, but I want to use the transfer parameter of the class constructor.

Currently my code looks like

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

How can I call the constructor with a parameter?

+6
source share
3 answers

You got close, getDeclaredConstructor() returns the Constructor object that is supposed to be used. In addition, you need to pass the String object to the newInstance() method of this Constructor .

 Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); Constructor<HsaInterface> ctor = _tempClass.getDeclaredConstructor(String.class); HsaInterface hsaAdapter = ctor.newInstance(aString); hsaAdapter.executeRequestTxn(txnData); 
+13
source
 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); 
+6
source
 Constructor constructor = _tempClass.getDeclaredConstructor(String.class); Object obj = constructor.newInstance("some string"); 
+1
source

Source: https://habr.com/ru/post/898518/


All Articles