使用接受字符串参数的构造函数实例化类对象? [英] Instantiate a class object with constructor that accepts a string parameter?

查看:342
本文介绍了使用接受字符串参数的构造函数实例化类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用它的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆