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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:00:31  来源:igfitidea点击:

Instantiate a class object with constructor that accepts a string parameter?

javahtmlreflectionconstructor

提问by HAMID

I would like to instantiate an object from its Classobject, using the constructor that accepts a single Stringargument.

我想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 JLabelobject with no text. I would like to use the JLabelconstructor that accepts a string as the initial text. Is there a way to select a specific constructor from a Classobject?

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

采纳答案by mwittrock

Class.newInstanceinvokes 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 Constructorinstance like this:

获取这样的Constructor实例:

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

The call to getConstructorspecifies that you want the constructor that takes a single Stringparameter. 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,

要调用参数化构造函数而不是零参数无参数构造函数,

  1. You have to get Constructorwith parameter types by passing types in Class[]for getDeclaredConstructormethod of Class
  2. You have to create constructor instance by passing values in Object[]for
    newInstancemethod of Constructor
  1. 您必须Constructor通过在Class[]forgetDeclaredConstructor方法中传递类型来获取参数类型 Class
  2. 您必须通过在Object[]for
    newInstance方法中传递值来创建构造函数实例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() 方法返回的引用。