使用Class.forName初始化一个类,该类具有一个接受参数

问题描述

||的构造函数。 我正在实例化这样的课程。
myObj = (myObj) Class.forName(\"fully qualified class name here\").newInstance();
我的疑问是,我们是否有一个接受参数的构造函数,如何像上面那样实例化它。 谢谢, 纳伦德拉     

解决方法

Class.getConstructor()
叫call2ѭ。例如,如果这是您在类
Foo
上的构造函数,则:
public Foo(String bar,int baz) {
}
您必须执行以下操作:
Constructor c = Class.forName(\"Foo\").getConstructor(String.class,Integer.TYPE);
Foo foo = (Foo) c.newInstance(\"example\",34);
您将必须知道需要将哪些参数传递给构造函数。如果不希望这样,则应考虑使用一个空的构造函数。然后使用方法设置通常传递给构造函数的内容。 有人可能会问您这里是否有正确的模式。您是否真的需要使用反射,也许有更好的方法?如果您知道已经要投射到对象上,为什么不正常地构造它呢?您可能想提供更多有关为什么需要这样做的背景信息。有充分的理由,但是您没有说明。     ,
newInstance()
总是调用默认构造函数。 如果要调用参数化的构造函数, 您必须通过传递
Class[]
获得带有参数类型的构造方法    用于Class的ѭ8of方法 您必须通过传递
Object[]
来创建构造函数实例    
newInstance()
构造方法 看一下示例代码。
import java.lang.reflect.*;

class NewInstanceDemo{
    public NewInstanceDemo(){
        System.out.println(\"Default constructor\");
    }
    public NewInstanceDemo(int a,long b){
        System.out.println(\"Two parameter constructor : int,long => \"+a+\":\"+b);
    }
    public NewInstanceDemo( int a,long b,String c){
        System.out.println(\"Three parameter constructor : int,long,String => \"+a+\":\"+b+\":\"+c);
    }
    public static void main(String args[]) throws Exception {

        NewInstanceDemo object = (NewInstanceDemo)Class.forName(\"NewInstanceDemo\").newInstance();
        Constructor constructor1 = NewInstanceDemo.class.getDeclaredConstructor( new Class[] {int.class,long.class});
        NewInstanceDemo object1 = (NewInstanceDemo)constructor1.newInstance(new Object[]{1,2});

    }
}
输出:
java NewInstanceDemo
Default constructor
Two parameter constructor : int,long => 1:2
查看oracle文档页面以获取更多详细信息。     ,如果要根据ѭ13选择要创建的对象类型,则很有可能,并且应将其替换为策略模式。