How to create instance of a class with the parameters in the constructor using reflection? [duplicate]
for example:
public class Test {
public static void main(String[] args) throws Exception {
Car c= (Car) Class.forName("Car").newInstance();
System.out.println(c.getName());
}
}
class Car {
String name = "Default Car";
String getName(){return this.name;}
}
clear code.
But, if I add constructor with params, some like this:
public Car(String name)
{this.name = name;}
I see: java.lang.InstantiationException
So, no I don't know, how pass constructor with params.
Please, help.
You need to say which constructor you want to use a pass it arguments.
Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");
If you are handling super / subclasses, or for whatever reason don't know exactly what Class is to be instantiated, the forName() method will be required also:
(ClassName) Class.forName([name_of_the_class])
.getConstructor([Type]).newInstance([Constructor Argument]);
This assumes name_of_the_class is a passed variable. Also, if the class is in a package, even if that package has been imported, you still have to explicitly stipulate the package in forName() (I think, I'm new to all this).
Class.forName([name_of_package].[name_of_class])