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.
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.
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.
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.
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");
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With