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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:47:02  来源:igfitidea点击:

Java Class Dynamically with Constructor parameter

javaclassdynamicinstantiation

提问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 Constructorobject you're supposed to be using. Also, you need to pass a Stringobject 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");