Dynamically Load the Class in Java


There are two ways in which you can dynamically load the Class in two ways.

1- With the help of  Class.ForNmae
Class someClass = Class.forName("SomeConcreteClass");
SomeConcreteClass conc= (SomeConcreteClass)someClass.newInstance();

2- With the help of  Some Class Loader
Class someClass = ClassLoader.loadClass("SomeConcreteClass");
SomeConcreteClass conc = (SomeConcreteClass)someClass.newInstance();
Then what is the difference between 

Class.forName() - will always use the class loader of the caller
it is also initialize the loaded class as well.

ClassLoader.loadClass() - you can specify the Different class loader,
it is not initialize until used for the first time delayed or lazy

 ClassLoader.getSystemClassLoader().loadClass("SomeClass");
 you can change it to your defined class loader

 // Get system class loader
 Field scl = ClassLoader.class.getDeclaredField("scl"); 
 // Set accessible
   scl.setAccessible(true); 
 // Update it to your class loader
 scl.set(null, new YourClassLoader()); 

3- With the help of  Some Class Loader with some more param
Class.forName(String, boolean, ClassLoader)
 String - for class name
 Boolean - to specify whether to initialize the class at the load time 
 ClassLoader - specify your own class loader




Comments