简体   繁体   English

使用接受字符串参数的构造函数实例化一个类对象?

[英]Instantiate a class object with constructor that accepts a string parameter?

I would like to instantiate an object from its Class object, using the constructor that accepts a single String argument. 我想使用接受单个String参数的构造函数从其Class对象实例化一个对象。

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. 但是,它实例化没有文本的JLabel对象。 I would like to use the JLabel constructor that accepts a string as the initial text. 我想使用接受字符串作为初始文本的JLabel构造函数。 Is there a way to select a specific constructor from a Class object? 有没有办法从Class对象中选择特定的构造函数?

Class.newInstance invokes the no-arg constructor (the one that doesn't take any parameters). Class.newInstance调用no-arg构造函数(不带任何参数的构造函数)。 In order to invoke a different constructor, you need to use the reflection package ( java.lang.reflect ). 为了调用不同的构造函数,您需要使用反射包( 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. getConstructor的调用指定您需要采用单个String参数的构造函数。 Now to create an instance: 现在创建一个实例:

Object o = cons.newInstance("JLabel");

And you're done. 而且你已经完成了。

PS Only use reflection as a last resort! PS只使用反射作为最后的手段!

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

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, 要调用参数化构造函数而不是零参数no-arg构造函数,

  1. You have to get Constructor with parameter types by passing types in Class[] for getDeclaredConstructor method of Class 你必须通过在Class[]Class getDeclaredConstructor方法传递类型来获取带有参数类型的Constructor
  2. You have to create constructor instance by passing values in Object[] for 您必须通过传递Object[]值来创建构造函数实例
    newInstance method of Constructor Constructor newInstance方法

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

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"); 的Class.forName( “RunDemo”); will load the RunDemo Class. 将加载RunDemo类。

Constructor c=RunDemo.class.getConstructor(String.class); 构造函数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. Constructor类的getConstructor()方法将返回具有String作为Argument的构造函数,其引用存储在Constructor类的对象'c'中。

RunDemo d=(RunDemo)c.newInstance("User"); 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. 构造函数类的newInstance()方法将实例化RundDemo类并返回对象的通用版本,并使用类型转换将其转换为RunDemo类型。

The object 'd' of RunDemo holds the reference returned by the newInstance() method. RunDemo的对象'd'保存newInstance()方法返回的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何实例化CellList <String> 使用TextCell对象作为CellList的参数的对象 <String> 构造函数? - How is it possible to instantiate a CellList<String> object using a TextCell object as parameter for CellList<String> constructor? 我可以通过类的构造函数实例化接口的对象吗 - Can I Instantiate an object of an Interface by the constructor of a class 为什么我不应该用构造函数实例化一个字符串对象? - Why should I not instantiate a string object with a constructor? 通用内部类构造函数接受所设置的不同类型参数? - Generic inner class constructor accepts different type parameter what is set? 从参数的 Class 实例化新的 object - Instantiate new object from Class of parameter Spring:根据String参数实例化一个类 - Spring: instantiate a class depending on String parameter 如何在Spring中实例化Class / Bean并在构造函数中传递参数 - How to instantiate a Class/Bean in Spring passing parameter in constructor 如何使用带有Groovy闭包的构造函数参数实例化Java抽象类 - How to instantiate a Java abstract class with a constructor parameter with a groovy closure 存储在引用中接受参数的构造函数 - Store constructor that accepts parameter in reference 转换器类getAsObject将参数传递给接受对象的Service类 - Converter class getAsObject pass parameter to Service class which accepts object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM