java 带有构造函数参数的动态Java类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7635313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Class Dynamically with Constructor parameter
提问by Makky
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 ?
如何使用参数调用构造函数?
回答by millimoose
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
.
你接近了,getDeclaredConstructor()
返回一个Constructor
你应该使用的对象。此外,您需要将一个String
对象传递给newInstance()
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);
回答by Saul
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);
回答by Bala R
Constructor constructor = _tempClass.getDeclaredConstructor(String.class);
Object obj = constructor.newInstance("some string");