Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 972
user471011 Avatar asked Jun 05 '11 07:06

user471011


People also ask

How do you create an instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

Which method is used to get constructor using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

How do you create a class object from a constructor in Java?

Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.

How do you create a reflection in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");


1 Answers

You need to say which constructor you want to use a pass it arguments.

Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen"); 
like image 52
Peter Lawrey Avatar answered Sep 29 '22 18:09

Peter Lawrey