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

时间:2008-10-24 17:49:00

标签: java constructor

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

8 个答案:

答案 0 :(得分:188)

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

答案 1 :(得分:86)

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

编辑:根据评论似乎指向类和方法名称对某些用户来说是不够的。有关详细信息,请查看getting constuctorinvoking it的文档。

答案 2 :(得分:65)

假设您有以下构造函数

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

答案 3 :(得分:16)

不要使用Class.newInstance();看到这个主题:Why is Class.newInstance() evil?

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

答案 4 :(得分:8)

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

答案 5 :(得分:7)

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

  1. 通过在Constructor中传递类型,获取带有参数类型的Class[] 适用于getDeclaredConstructor
  2. Class方法
  3. 通过传递Object[]中的值来创建构造函数实例 newInstance
  4. 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
    

答案 6 :(得分:1)

您可以使用Class的getDeclaredConstructor方法。它需要一组类。这是一个经过测试和运作的例子:

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

答案 7 :(得分:1)

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

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

相关问题