9

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 ?

3 Answers 3

16

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

1
Constructor constructor = _tempClass.getDeclaredConstructor(String.class);
Object obj = constructor.newInstance("some string");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.