Class Loader Java: Here, an object of a class is created without using new keyword using java.lang.ClassLoader. See the code.
public class Demo
{
int x = 10;
public static void main(String args[]) throws Exception
{
Class cls = Class.forName("Demo");
ClassLoader cLoader = cls.getClassLoader();
Class cl = cLoader.loadClass("Demo");
Demo d1 = (Demo) cl.newInstance();
System.out.println(d1.x); // prints 10
}
}
Class cls = Class.forName(“Demo”);
The forName() method of class Class returns an object of Class. Now cls represents Demo class.
ClassLoader cLoader = cls.getClassLoader();
Class cl = cLoader.loadClass(“Demo”);
getClassLoader() method of Class returns an object of ClassLoader (it is abstract class). loadClass() returns an object Class.
Demo d1 = (Demo) cl.newInstance();
The newInstance() method returns an Object and is type casted to Demo. Now Demo object d1 is created without using new keyword. It is a very round about process. The best one is using cloning.
Would you like to know all the 5 styles of creating Java object without using new keyword?