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.
Class c = Class.forName(args[0]);
This gets a Class<?>
object...
Constructor ctr = c.getDeclaredConstructor(new Class[]{String.class})
and this gets a constructor for that class which argument is a single String.
Once you have that you can invoke ctr.newInstance(someString)
.
You have a problem though, in that you don't really know the class here. You should at least have an idea of a common subtype, otherwise all you'll ever get is an Object
...
1- To create a class instance at runtime using reflection :
Class classToInstantiate = Class.forName(className);
Constructor<?> theClassInstructor = classToInstantiate.getDeclaredConstructor(<parametersClasses>);
Object instance = theClassInstructor.newInstance(<parameters>);
With:
parametersClasses
array of the classes of the constructor parameters, for example if the constructor uses a String and an Integer parameter you write : getDeclaredConstructor(new Class[]{String.class,Integer.class});
parameters
are the actual values of the parameters to use when instantiating.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.