Some times it's not necessary to create object for the class to call is constructors and methods. You can call methods of class without creating direct object. It's very easy to call a constructor with parameter.
import java.lang.reflect.*;
import java.util.*;
class RunDemo
{
public RunDemo(String s)
{
System.out.println("Hello, I'm a constructor. Welcome, "+s);
}
static void show()
{
System.out.println("Hello.");
}
}
class Democlass
{
public static void main(String args[])throws Exception
{
Class.forName("RunDemo");
Constructor c = RunDemo.class.getConstructor(String.class);
RunDemo d = (RunDemo)c.newInstance("User");
d.show();
}
}
the output will be:
Hello, I'm a constructor. Welcome, User
Hello.
Class.forName("RunDemo"); will load the RunDemo Class.
Constructor c=RunDemo.class.getConstructor(String.class); getConstructor() method of Constructor class will return the constructor which having String as Argument and its reference is stored in object 'c' of Constructor class.
RunDemo d=(RunDemo)c.newInstance("User"); the method newInstance() of Constructor class will instantiate the RundDemo class and return the Generic version of object and it is converted into RunDemo type by using Type casting.
The object 'd' of RunDemo holds the reference returned by the newInstance() method.