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

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


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

or

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


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.


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 argumentscArg[0] = Long.class; //First argument is of *object* type LongcArg[1] = String.class; //Second argument is of *object* type StringcArg[2] = int.class; //Third argument is of *primitive* type intLong l = new Long(88);String s = "text";int i = 5;classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);