How to create instance of a class with the parameters in the constructor using reflection?
61,882
Solution 1
You need to say which constructor you want to use a pass it arguments.
Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");
Solution 2
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])
Related videos on Youtube
Author by
user471011
Updated on January 28, 2020Comments
-
user471011 over 4 years
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.
-
mcoolive over 6 yearsFor native types, use (for example) Integer.TYPE instead of Integer.class
-
Vishy over 6 years@mcoolive or int.class