Java 使用接受字符串参数的构造函数实例化一个类对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3574065/
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
Instantiate a class object with constructor that accepts a string parameter?
提问by HAMID
I would like to instantiate an object from its Class
object, using the constructor that accepts a single String
argument.
我想Class
使用接受单个String
参数的构造函数从其对象实例化一个对象。
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?
但是,它实例化了JLabel
没有文本的对象。我想使用JLabel
接受字符串作为初始文本的构造函数。有没有办法从Class
对象中选择特定的构造函数?
采纳答案by mwittrock
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
).
Class.newInstance
调用无参数构造函数(不带任何参数的构造函数)。为了调用不同的构造函数,您需要使用反射包 ( java.lang.reflect
)。
Get a Constructor
instance like this:
获取这样的Constructor
实例:
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:
对 的调用getConstructor
指定您想要采用单个String
参数的构造函数。现在创建一个实例:
Object o = cons.newInstance("JLabel");
And you're done.
你已经完成了。
P.S. Only use reflection as a last resort!
PS 只使用反射作为最后的手段!
回答by Jothi
The following will work for you. Try this,
以下内容对您有用。尝试这个,
Class[] type = { String.class };
Class classDefinition = Class.forName("javax.swing.JLabel");
Constructor cons = classDefinition .getConstructor(type);
Object[] obj = { "JLabel"};
return cons.newInstance(obj);
回答by Ravindra babu
Class.forName("className").newInstance()
always invokes no argument default constructor.
Class.forName("className").newInstance()
始终调用无参数默认构造函数。
To invoke parametrized constructor instead of zero argument no-arg constructor,
要调用参数化构造函数而不是零参数无参数构造函数,
- You have to get
Constructor
with parameter types by passing types inClass[]
forgetDeclaredConstructor
method ofClass
- You have to create constructor instance by passing values in
Object[]
fornewInstance
method ofConstructor
- 您必须
Constructor
通过在Class[]
forgetDeclaredConstructor
方法中传递类型来获取参数类型Class
- 您必须通过在
Object[]
fornewInstance
方法中传递值来创建构造函数实例Constructor
Example code:
示例代码:
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection( String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
output:
输出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
回答by reshmi reddy
Some times it's not necessary to create object for the class to call is constructors and methods. You can call methods of class without creating direct object. It's very easy to call a constructor with parameter.
有时没有必要为类创建对象来调用构造函数和方法。您可以在不创建直接对象的情况下调用类的方法。调用带参数的构造函数非常容易。
import java.lang.reflect.*;
import java.util.*;
class RunDemo
{
public RunDemo(String s)
{
System.out.println("Hello, I'm a constructor. Welcome, "+s);
}
static void show()
{
System.out.println("Hello.");
}
}
class Democlass
{
public static void main(String args[])throws Exception
{
Class.forName("RunDemo");
Constructor c = RunDemo.class.getConstructor(String.class);
RunDemo d = (RunDemo)c.newInstance("User");
d.show();
}
}
the output will be:
输出将是:
Hello, I'm a constructor. Welcome, User
大家好,我是施工员。欢迎,用户
Hello.
你好。
Class.forName("RunDemo");will load the RunDemo Class.
Class.forName("RunDemo"); 将加载 RunDemo 类。
Constructor c=RunDemo.class.getConstructor(String.class);getConstructor() method of Constructor class will return the constructor which having String as Argument and its reference is stored in object 'c' of Constructor class.
构造函数 c=RunDemo.class.getConstructor(String.class); Constructor 类的 getConstructor() 方法将返回以 String 作为参数的构造函数,其引用存储在 Constructor 类的对象“c”中。
RunDemo d=(RunDemo)c.newInstance("User");the method newInstance() of Constructor class will instantiate the RundDemo class and return the Generic version of object and it is converted into RunDemo type by using Type casting.
RunDemo d=(RunDemo)c.newInstance("用户"); Constructor 类的 newInstance() 方法将实例化 RundDemo 类并返回对象的 Generic 版本,并通过类型转换将其转换为 RunDemo 类型。
The object 'd' of RunDemo holds the reference returned by the newInstance() method.
RunDemo 的对象 'd' 保存了 newInstance() 方法返回的引用。