Breaking News
Home / Java / Java Tutorials / What is Dynamic Class Loading In Java?

What is Dynamic Class Loading In Java?

Dynamic Class Loading in Java The JVM creates ClassLoaders that loads the classes as required during program execution. In case of Dynamic class loading, a class is loaded programatically 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 class name 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 = “”;
Class cls = Class.forName(className);
Manager mgr = (Manager)cls.newInstance();

ClassLoader Class

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 some where over the network.

For classes to be loaded outside CLASSPATH, the class loader 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 required 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.[pb_builder]

Check Also

Have a Question

How to select a JVM Analyzing Tool?

A JVM monitoring tool also know as a Diagnostic might be needed to fine tune …

Advertisment ad adsense adlogger