Can I use Class.newInstance() with constructor arguments?

JavaConstructor

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

or

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

Solution 2 - Java

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.

Solution 3 - Java

Assuming you have the following constructor

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

    }
}

You will need to show you intend to use this constructor like so:

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

Solution 4 - Java

Do not use Class.newInstance(); see this thread: Why is Class.newInstance() evil?

Like other answers say, use Constructor.newInstance() instead.

Solution 5 - Java

Solution 6 - Java

Follow below steps to call parameterized consturctor.

  1. Get Constructor with parameter types by passing types in Class[] for getDeclaredConstructor method of Class
  2. Create constructor instance by passing values in Object[] for
    newInstance method of Constructor

Example code:

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

output:

java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow

Solution 7 - Java

You can use the getDeclaredConstructor method of Class. It expects an array of classes. Here is a tested and working example:

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

Solution 8 - Java

I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html

Although it seems a dead thread, someone might find it useful

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomarView Question on Stackoverflow
Solution 1 - JavajsightView Answer on Stackoverflow
Solution 2 - JavaMarkoView Answer on Stackoverflow
Solution 3 - JavaMartin KonecnyView Answer on Stackoverflow
Solution 4 - JavaChris Jester-YoungView Answer on Stackoverflow
Solution 5 - JavainyView Answer on Stackoverflow
Solution 6 - JavaRavindra babuView Answer on Stackoverflow
Solution 7 - JavaLajos ArpadView Answer on Stackoverflow
Solution 8 - JavaSpyros DoulgeridisView Answer on Stackoverflow