256

I would like to use Class.newInstance() but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?

4

8 回答 8

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

or

obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
于 2008-10-24T17:52:26.553 回答
91
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);

Edit: according to the comments seems like pointing class and method names is not enough for some users. For more info take a look at the documentation for getting constuctor and invoking it.

于 2008-10-24T17:51:53.933 回答
83

假设您有以下构造函数

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

    }
}

你需要表明你打算像这样使用这个构造函数:

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);
于 2014-06-08T19:15:07.283 回答
20

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

就像其他答案说的那样,Constructor.newInstance()改用。

于 2008-10-24T20:43:51.713 回答
9

You can get other constructors with getConstructor(...).

于 2008-10-24T17:51:03.857 回答
8

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

  1. Constructor通过将类型传入 Class[] forgetDeclaredConstructor方法获取参数类型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"});

    }
}

输出:

java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
于 2016-10-29T10:40:27.510 回答
1

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

虽然它似乎是一个死线程,但有人可能会发现它很有用

于 2014-04-24T11:31:04.593 回答
1

你可以使用getDeclaredConstructorClass的方法。它需要一个类数组。这是一个经过测试的工作示例:

public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
    try
    {
        JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
        if (parentComponent != null)
        {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        else
        {
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        }
        frame.setLocationRelativeTo(parentComponent);
        frame.pack();
        frame.setVisible(true);
    }
    catch (InstantiationException instantiationException)
    {
        ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
    }
    catch(NoSuchMethodException noSuchMethodException)
    {
        //ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
        ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
    }
    catch (IllegalAccessException illegalAccessException)
    {
        ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
    }
    catch (InvocationTargetException invocationTargetException)
    {
        ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
    }
    finally
    {
        return null;
    }
}
于 2013-07-02T14:56:30.040 回答