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

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

下面是一些接近我想要的代码:

Object object = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
object = classDefinition.newInstance();

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

100560 次浏览

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

Class.forName("className").newInstance() always invokes no argument default constructor.

To invoke parametrized constructor instead of zero argument no-arg constructor,

  1. You have to get Constructor with parameter types by passing types in Class[] for getDeclaredConstructor method of Class
  2. You have to create constructor instance by passing values in Object[] for
    newInstance method of 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

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.

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.

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.

The object 'd' of RunDemo holds the reference returned by the newInstance() method.