Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What does class newInstance () do?

Class. newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException .

Can class constructor have arguments?

If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.

Why newInstance method was deprecated?

newInstance(). The reason for the deprecation is that that path bypasses compile-time exception checking.


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

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

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


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