使用接受字符串参数的构造函数实例化类对象? [英] Instantiate a class object with constructor that accepts a string parameter?
问题描述
我想用它的 Class
对象实例化一个对象,使用接受一个 String
参数的构造函数。
以下是一些接近我想要的代码:
pre $ Object object = null;
Class classDefinition = Class.forName(javax.swing.JLabel);
object = classDefinition.newInstance();
然而,它将 JLabel
对象实例化为没有文字。我想使用接受字符串作为初始文本的 JLabel
构造函数。有没有一种方法可以从 Class
对象中选择特定的构造函数?
Class.newInstance
调用no-arg构造函数(不带任何参数的构造函数)。为了调用不同的构造函数,您需要使用反射包( java.lang.reflect
)。
获得一个构造函数
像这样的实例:
Class <?> cl = Class.forName(javax.swing.JLabel);
构造函数<?> cons = cl.getConstructor(String.class);
调用 getConstructor
指定您想要该构造函数接受一个 String
参数。现在创建一个实例:
Object o = cons.newInstance(JLabel);
完成了。
PS只能使用反射作为最后的手段!
I would like to instantiate an object from its Class
object, using the constructor that accepts a single String
argument.
Here is some code that approaches what I want:
Object object = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
object = classDefinition.newInstance();
However, it instantiates the JLabel
object with no text. I would like to use the JLabel
constructor that accepts a string as the initial text. Is there a way to select a specific constructor from a Class
object?
Class.newInstance
invokes the no-arg constructor (the one that doesn't take any parameters). In order to invoke a different constructor, you need to use the reflection package (java.lang.reflect
).
Get a Constructor
instance like this:
Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);
The call to getConstructor
specifies that you want the constructor that takes a single String
parameter. Now to create an instance:
Object o = cons.newInstance("JLabel");
And you're done.
P.S. Only use reflection as a last resort!
这篇关于使用接受字符串参数的构造函数实例化类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!