The JVM creates ClassLoaders that loads the classes as required during program execution. In case of Dynamic class loading, a class is loaded programmatically instructing the ClassLoader to load it via API. The JVM does not know to load this class as it not declared in the code instead the JVM class loader is asked to load it dynamically by specifying the classname as String.
Creating Object Instance of the loaded Class
Further once the class is loaded, an instance of the class can created by invoking the class.newInstance() method on the class object e.g.
String className = “abc.xyz.Manager”; Class cls = Class.forName(className); Manager mgr = (Manager)cls.newInstance(); mgr.someMethod();
The ClassLoader class allows you to define a custom class loaders for the classes that are to be loaded from outside your CLASSPATH e.g. these classes could be available somewhere over the network.
For classes to be loaded outside CLASSPATH, the classloader needs to convert the class byte stream into a class descriptor. The ClassLoader an abstract class that provides the following methods:
- defineClass() – is used to convert class bytes into a class descriptor
- loadClass() – is used to load a class from its source, usually a network location.
- resolveClass() – is used to resolve all the classes referenced by a particular class by loading and defining those classes.
- findSystemClass() – is used to loaded classes that are located with the CLASSPATH and hence does not require a custom class loader.
- findLoadedClass() – is used to find a class that is already loaded.
- findLocalClass() – is used to find a class on the local system.
Dynamic Class Loading Example
Consider the following example to demonstrate Dynamic Class Loading:
In this example of a Data Access Object, the JDBC Driver class is loaded dynamically. by using the Class.forName(driverClass); If that class is not found in the any of the class-paths then the ClassLoader will throw a ClassNotFoundException