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

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

问题描述

我想从它的 Class 对象实例化一个对象,使用接受单个 String 参数的构造函数.

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();

然而,它实例化了没有文本的 JLabel 对象.我想使用接受字符串作为初始文本的 JLabel 构造函数.有没有办法从 Class 对象中选择特定的构造函数?

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 调用无参数构造函数(不带任何参数的构造函数).为了调用不同的构造函数,您需要使用反射包(java.lang.reflect).

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).

像这样获取一个 Constructor 实例:

Get a Constructor instance like this:

Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);

getConstructor 的调用指定您需要采用单个 String 参数的构造函数.现在创建一个实例:

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

大功告成.

附言仅将反射作为最后的手段!

P.S. Only use reflection as a last resort!

这篇关于使用接受字符串参数的构造函数实例化一个类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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