Static Vs Dynamic class loading in Java

The class loader concept, which stands as a fundamental pillar within the Java virtual machine (JVM), elucidates the intricate process of transforming a designated class into the fundamental components essential for its successful implementation. By virtue of the existence of class loaders, the Java runtime is absolved from the requirement of possessing any knowledge pertaining to files and file systems during the execution of Java programs.

Static class loading

In static class loading, classes are inherently loaded in a static manner through Java's esteemed "new" operator. In this scenario, the acquisition of class definitions and the subsequent instantiation of objects take place during the compile time phase, thereby maintaining an environment of efficiency and precision.

This technique grants the compiler the ability to thoroughly analyze the code and resolve dependencies, allowing for the seamless generation of the necessary instructions for object creation. Consequently, this streamlined approach ensures that the class is readily available for utilization at runtime, eliminating the need for dynamic resolution mechanisms and further bolstering the performance and reliability of the Java program.

class TestClass { public static void main(String args[]) { TestClass tc = new TestClass(); } }

Dynamic class loading

Dynamic loading is an innovative and advanced technique employed to dynamically invoke the functions of a class loader during runtime, thereby enhancing the flexibility and adaptability of software systems. This approach allows for the seamless incorporation of external components and resources into an application, even when the specific name of the class is not ascertainable at compile time.

Dynamic class loading serves as an indispensable mechanism for accommodating unknown class names by using the power of dynamic loading. By deferring the resolution of class names until runtime, this technique facilitates the seamless integration of external modules, libraries, or plugins, thereby extending the functionality and versatility of an application.

At the core of this technique lies the capability to programmatically access and invoke the functions of a class loader during the execution of a program. The class loader, acting as a dynamic gateway, plays a key role in dynamically locating, loading, and instantiating classes as needed, thus enabling the system to adapt to changing requirements and scenarios.

Syntax
Class.forName (String className);

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Once the class is dynamically loaded the class.newInstance () method returns an instance of the loaded class.

The Java model loads classes as needed and need not know the name of all classes in a collection before any one of its classes can be loaded and run.