开发者

Java Class Dynamically with Constructor parameter

开发者 https://www.devze.com 2023-04-10 12:26 出处:网络
I have to create a class dynamically but I want to use class constructor passing parameter. Currently my code looks like

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号