Java reflection - dynamic class loading with example

UdaysinhUdaysinh
3 min read

https://examples.javacodegeeks.com/core-java/dynamic-class-loading-example/

What is dynamic class loading?

Dynamic Java Class allows the Java platform with the ability to install software components at run-time where you can load your classes in a lazy loading manner which means that classes are loaded on demand and at the last moment possible.

What does that actually mean?

Normally if you want to use certain class and its methods, you import the class and invoke the methods. This is visible to compiler and IDE and is evaluated during compile time to be safe. When you load a class dynamically, you reference the class and its method names as strings. Compiler can't compile this and this is evaluated during runtime.

How does it do it? -> Classloader

A class loader is an object that is responsible for loading classes, it is an abstract class. Class loader generates the data referring the class using a class binary name which is constituted of package name and class name like java.lang.String.

When a class is loaded, all classes it references are loaded too. This class loading pattern happens recursively, until all classes needed are loaded. This may not be all classes in the application. Unreferenced classes are not loaded until the time they are referenced.

How does class loader works?

The ClassLoader class mechanism works based on a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When requested to find a class or resource, the below steps are followed:

  1. A ClassLoader instance checks if the class was already loaded.
  2. If not loaded, it delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself.
  3. If parent class loader cannot load class, it attempt to load the class or resource by itself.

Can you show me an example?

Dynamic Java Class loading is mainly using the Java Reflection. Java Reflection provides ability to examine or modify the runtime behavior of applications running in the JVM. Also, it is used to determine methods and attributes that will be used in a certain class at runtime.

package com.example;
public class MyClass {

    public void sayHello() {
        System.out.println("Hello world from the loaded class!!");
    }

}

MyClass.java -> Class to be loaded dynamically

package com.example;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class JavaClassLoader extends ClassLoader {

    public void invokeClassMethod(String classBinName, String methodName){

        try {

            // Create a new JavaClassLoader 
            ClassLoader classLoader = this.getClass().getClassLoader();

            // Load the target class using its binary name
            Class loadedMyClass = classLoader.loadClass(classBinName);

            System.out.println("Loaded class name: " + loadedMyClass.getName());

            // Create a new instance from the loaded class
            Constructor constructor = loadedMyClass.getConstructor();
            Object myClassObject = constructor.newInstance();

            // Getting the target method from the loaded class and invoke it using its name
            Method method = loadedMyClass.getMethod(methodName);
            System.out.println("Invoked method name: " + method.getName());
            method.invoke(myClassObject);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

JavaClassLoader.java -> Class which loads the dynamic class

package com.example;

public class ClassLoaderTest extends JavaClassLoader {

    public static void main(String[] args) {

        JavaClassLoader javaClassLoader = new JavaClassLoader();
        javaClassLoader.invokeClassMethod("com.example.MyClass", "sayHello");

    }

}

ClassLoaderTest.java -> Running the example

Output ->

  • Loaded class name: com.example.MyClass
  • Invoked method name: sayHello
  • Hello world from the loaded class !!!
0
Subscribe to my newsletter

Read articles from Udaysinh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Udaysinh
Udaysinh

Lead software engineer working in financial industry with expertise in backend technologies, fascinated by system design and architecture, always keen to learn what's new