Dynamic Class Loading

The java.lang.Class provides the forName() method which allows you to load a class dynamically. The argument to this method is the fully qualified name, i.e., the complete name of a class including the package hierarchy. So, if you want to load the Vector class from the java.util package, its fully qualified name would be “java.util.Vector”.

The following code snippet demonstrates dynamic class loading:

 // DynamicClassLoadingDemo.java// Importsimport java.util.List;/** Demonstrates the use of dynamic class loading. */public class DynamicClassLoadingDemo {  /** Starts the demo. */  public void startDemo()         throws ClassNotFoundException, InstantiationException,                IllegalAccessException {    Class c;    List list;    c    = Class.forName("java.util.ArrayList");    list = (List)c.newInstance();    // Initialize the list    list.add("Element #1");    list.add("Element #2");    // Display    System.out.println("List: " + list);  }  /** Main. */  public static void main(String[] args) {    try {      // Initialize and start the demo      DynamicClassLoadingDemo demo = new DynamicClassLoadingDemo();      demo.startDemo();    }    catch(Exception ex) {      ex.printStackTrace();    }  }}


The main() method creates an instance of the demo class, and invokes the startDemo() method. This method uses the Class.forName() method to load an implementation of the java.util.List interface. To create an object of the newly loaded class, you call the newInstance() method on it. This uses the default constructor of the class. You’ll need to typecast this object so that you can invoke methods on it. Then add a couple of elements to the list, and display it.

As you can see, the java.util.ArrayList class is being loaded dynamically. Later, if you find a better class to meet your requirements, you can substitute it for the ArrayList. Further, you can also use a property file to store the class name, instead of hardcoding this string in a program.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist