我可以将Class.newInstance()与构造函数参数一起使用吗?

233 java constructor

我想使用,Class.newInstance()但我实例化的类没有一个无效的构造函数.因此,我需要能够传递构造函数参数.有没有办法做到这一点?

jsi*_*ght 197

MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
Run Code Online (Sandbox Code Playgroud)

  • 只是澄清 - "getDeclaredConstructor"不是静态方法,你必须在特定类的Class实例上调用它. (23认同)

Mar*_*rko 87

myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
Run Code Online (Sandbox Code Playgroud)

编辑:根据评论看起来像指向类和方法名称是不够的一些用户.有关更多信息,请查看获取constuctor调用它的文档.

  • 答案没有说明你如何传递args,或者展示一个例子.这只是猜测. (18认同)
  • 它应该是getDeclaredConstructor(单数)吗? (2认同)
  • @ryvantage不会使它看起来像一个静态方法,因为它在"myObject"实例上被调用.它只是方法调用的菊花链.也不确定为什么这个答案对55个人有用,因为它错了,正确的一个在下面! (2认同)

Mar*_*cny 68

假设您有以下构造函数

class MyClass {
    public MyClass(Long l, String s, int i) {

    }
}
Run Code Online (Sandbox Code Playgroud)

您将需要显示您打算使用此构造函数,如下所示:

Class classToLoad = MyClass.class;

Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int

Long l = new Long(88);
String s = "text";
int i = 5;

classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
Run Code Online (Sandbox Code Playgroud)


Chr*_*ung 18

不要用Class.newInstance(); 看到这个帖子:为什么Class.newInstance()是邪恶的?

像其他答案一样,请Constructor.newInstance()改用.


iny*_*iny 8

您可以使用getConstructor(...)获取其他构造函数.


Rav*_*abu 8

按照以下步骤调用参数化的consturctor.

  1. Constructor通过Class[] 为for getDeclaredConstructor方法传递类型来获取参数类型 Class
  2. 通过传递Object[]for
    newInstance方法的值来创建构造函数实例Constructor

示例代码:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
Run Code Online (Sandbox Code Playgroud)