How can we we create an object of a class with parametrized constructor,and the name of the class would be given to us at the run time as command line argument.
That JavaDoc for Class.getDeclaredConstructor is pretty clear:
Returns a
Constructor
object that reflects the specified constructor of the class or interface represented by thisClass
object. TheparameterTypes
parameter is an array ofClass
objects that identify the constructor's formal parameter types, in declared order.
... so in your case it's getting a Constructor
object that represents a constructor with one argument, which is a String
(new Class[] {String.class}
constructs a Class[]
with a single entry which is the Class
object representing java.lang.String
). You can call newInstance("some string")
on that object in order to invoke the constructor and return a new instance of the target class.
In practice you probably need to use getConstructor
instead of getDeclaredConstructor
as the latter will return any constructor that matches the specified parameter types, including ones that would not normally be accessible from outside (e.g. private
ones). Conversely, getConstructor
will only return public
constructors.