I have to create a class dynamically but I want to use class constructor passing parameter.
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 the parameter ?
A Constructor which has parameters in it called as Parameterized Constructors, this constructor is used to assign different values for the different objects. In the below example we have a constructor for the Car class which takes in the the value and sets to the property, lets try to set the value for the property “carColor”
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type. There are two types of constructors parameterized constructors and no-arg constructors.
The difference is constructor is executed automatically and the normal method is explicitly called. Constructor name and its class name should be same. The Constructor does not have a return type. For each object, the constructor is called that too when the object is created. Constructors can also take arguments, so can be overloaded.
As we discussed in the Java Constructor tutorial that a constructor is a special type of method that initializes the newly created object. We can have any number of Parameterized Constructor in our class. In this example, I have implemented four constructors: one is default constructor and other three are parameterized.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With