我想使用class . newinstance(),但我实例化的类没有null构造函数。因此,我需要能够传入构造函数参数。有办法做到这一点吗?


当前回答

按照以下步骤调用参数化构造函数。

通过在Class[]中传递类型获取带参数类型的构造函数 用于类的getDeclaredConstructor方法 通过在Object[]中传递值创建构造函数实例 构造函数的newInstance方法

示例代码:

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

    }
}

输出:

java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow

其他回答

按照以下步骤调用参数化构造函数。

通过在Class[]中传递类型获取带参数类型的构造函数 用于类的getDeclaredConstructor方法 通过在Object[]中传递值创建构造函数实例 构造函数的newInstance方法

示例代码:

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

    }
}

输出:

java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow

我觉得这正是你想要的 http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html

虽然它看起来是一条死线,但有人可能会发现它有用

可以使用getConstructor(…)获取其他构造函数。

myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);

编辑:根据评论似乎指向类和方法名是不够的一些用户。要了解更多信息,请参阅获取构造函数并调用它的文档。

MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");

or

obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");