JVM.Classloading.What is the Class.forName() method, and how does it work?

The Class.forName() method in Java is a built-in reflection mechanism used to dynamically load a class at runtime. It returns a Class<?> object representing the loaded class.

Syntax

Class<?> cls = Class.forName("com.example.MyClass");

Here, "com.example.MyClass" is the fully qualified class name.

How Class.forName() Works

  1. Loads the specified class into memory if it is not already loaded.
  2. Performs class linking, which includes verification, preparation, and resolution.
  3. Initializes the class, meaning it executes static blocks and initializes static fields.

Examples

1. Loading and Instantiating a Class Dynamically

public class Example {
    static {
        System.out.println("Example class initialized");
    }
}
public class ReflectionTest {
    public static void main(String[] args) throws Exception {
        // Dynamically load the Example class
        Class<?> cls = Class.forName("Example");
    }
}

Output

Example class initialized

This confirms that the class is loaded and initialized.

Creating an Instance Dynamically

public class Example {
    public void showMessage() {
        System.out.println("Hello from Example class");
    }
}
public class DynamicInstantiation {
    public static void main(String[] args) throws Exception {
        // Load and create an instance of Example class dynamically
        Class<?> cls = Class.forName("Example");
        Object obj = cls.getDeclaredConstructor().newInstance();
        
        // Invoke method dynamically
        cls.getMethod("showMessage").invoke(obj);
    }
}

Output

Hello from Example class

Variants of Class.forName()

1. Default Behavior (Loads and Initializes)

Class<?> cls = Class.forName("Example");

Loads and initializes the class.Executes static blocks.

Load Without Initialization

Class<?> cls = Class.forName("Example", false, ClassLoader.getSystemClassLoader());

Loads the class without initializing it.Useful when you want to inspect the class but delay execution of static blocks.

Use Cases of Class.forName()

  1. JDBC Database Connections
Class.forName("com.mysql.cj.jdbc.Driver"); // Dynamically loads JDBC driver

Dependency Injection (Dynamically loading implementation classes)

Plugin-based architectures.

Reflection API for dynamic method calls.

Avoiding hardcoded dependencies in frameworks

Key Takeaways

  • Class.forName("ClassName") loads and initializes the class.
  • It is used for dynamic loading in frameworks like JDBC and Spring.
  • A variant allows loading without initialization to defer static block execution.
  • Helps implement reflection-based techniques like dependency injection.

Would you like a deeper dive into any specific aspect? 😊

This entry was posted in Без рубрики. Bookmark the permalink.