The Wayback Machine - https://web.archive.org/web/20240725054139/https://www.geeksforgeeks.org/classloader-in-java/
Open In App

ClassLoader in Java

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The Java ClassLoader is an integral part of the Java Runtime Environment (JRE) that dynamically loads Java classes into the Java Virtual Machine (JVM). The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE, and these ClassLoaders load classes into memory dynamically.

ClassLoaders play a crucial role in Java’s ability to dynamically load classes into memory as needed, enabling flexibility and efficiency in Java applications.

Types of ClassLoaders in Java

Java’s ClassLoaders are categorized into different types, each responsible for loading classes from specific locations:

1. Bootstrap ClassLoader (Primordial ClassLoader):

  • The Bootstrap ClassLoader is a machine code responsible for initiating the JVM’s operations.
  • In Java versions up to 8, it loaded core Java files from rt.jar. However, starting from Java 9, it loads core Java files from the Java Runtime Image (JRT).
  • Bootstrap ClassLoader operates independently without any parent ClassLoaders.

2. Platform Class Loader (Extension ClassLoader):

  • In Java versions before Java 9, there was an Extension ClassLoader, but from Java 9 onwards, it’s referred to as the Platform Class Loader.
  • It loads platform-specific extensions from the JDK’s module system.
  • Platform Class Loader loads files from the Java runtime image or from any other module specified by the system property java.platform or –module-path.

3. System ClassLoader (Application ClassLoader):

  • Also known as the Application ClassLoader, it loads classes from the application’s classpath.
  • It is a child of the Platform Class Loader.
  • Classes are loaded from directories specified by the environment variable CLASSPATH, the -classpath or -cp command-line option.

Principles of Functionality of a Java ClassLoader

Java ClassLoaders operate based on specific principles:

1. Delegation Model:

  • ClassLoaders follow a delegation hierarchy algorithm.
  • When the JVM encounters a class, it checks if it’s already loaded. If not, it delegates the loading process through a chain of ClassLoaders.
  • The delegation hierarchy starts from the Application ClassLoader, then moves to the Platform Class Loader, and finally to the Bootstrap ClassLoader.
  • Each ClassLoader in the hierarchy searches for the class in its defined locations and delegates the search if necessary.

2. Visibility Principle:

  • Classes loaded by parent ClassLoaders are visible to child ClassLoaders, but not vice versa.
  • This ensures encapsulation and prevents conflicts between classes loaded by different ClassLoaders.

3. Uniqueness Property:

  • ClassLoaders ensure that classes are loaded only once to maintain uniqueness.
  • If a parent ClassLoader cannot find a class, only then the current instance attempts to load it.

Methods of java.lang.ClassLoader

Several methods in java.lang.ClassLoader facilitate the loading of classes:

  • loadClass(String name, boolean resolve): Loads classes referenced by the JVM, resolving them if necessary.
  • defineClass(): Defines a byte array as an instance of a class. Throws ClassFormatError if the class is invalid.
  • findClass(String name): Finds a specified class without loading it.
  • findLoadedClass(String name): Verifies if the class is already loaded.
  • Class.forName(String name, boolean initialize, ClassLoader loader): Loads and initializes a class, allowing the specification of a ClassLoader. If the ClassLoader parameter is null, the Bootstrap ClassLoader is used by default.

Example:

// Code executed before class loading
Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass("com.example.MyClass");
  • ClassLoader in Java

Java ClassLoader Functionality Principles

Principles of functionality are the set of rules or features on which a Java ClassLoader works. There are three principles of functionality, they are:

  1. Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the Delegation Hierarchy Algorithm to Load the classes into the Java file. The ClassLoader works based on a set of operations given by the delegation model. They are:
    • ClassLoader always follows the Delegation Hierarchy Principle.
    • Whenever JVM comes across a class, it checks whether that class is already loaded or not.
    • If the Class is already loaded in the method area then the JVM proceeds with execution.
    • If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader.
    • Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader.
    • Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader.
    • Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader.
    • Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated.
  2. Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class has been loaded by the Extension ClassLoader, then that class is only visible to the Extension ClassLoader and Application ClassLoader but not to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an exception java.lang.ClassNotFoundException.
  3. Uniqueness Property: The Uniqueness Property ensures that the classes are unique and there is no repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded by the child classloaders. If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself.

Key Methods of java.lang.ClassLoader:

After the JVM requests for the class, a few steps are to be followed in order to load a class. The Classes are loaded as per the delegation model but there are a few important Methods or Functions that play a vital role in loading a Class.

  1. loadClass(String name, boolean resolve): This method is used to load the classes which are referenced by the JVM. It takes the name of the class as a parameter. This is of type loadClass(String, boolean).
  2. defineClass(): The defineClass() method is a final method and cannot be overridden. This method is used to define a array of bytes as an instance of class. If the class is invalid then it throws ClassFormatError.
  3. findClass(String name): This method is used to find a specified class. This method only finds but doesn’t load the class.
  4. findLoadedClass(String name): This method is used to verify whether the Class referenced by the JVM was previously loaded or not.
  5. Class.forName(String name, boolean initialize, ClassLoader loader): This method is used to load the class as well as initialize the class. This method also gives the option to choose any one of the ClassLoaders. If the ClassLoader parameter is NULL then Bootstrap ClassLoader is used.

Example: The following code is executed before a class is loaded: 

Java
protected synchronized Class&lt;?&gt;
loadClass(String name, boolean resolve)
    throws ClassNotFoundException
{
    Class c = findLoadedClass(name);
    try {
        if (c == NULL) {
            if (parent != NULL) {
                c = parent.loadClass(name, false);
            }
            else {
                c = findBootstrapClass0(name);
            }
        }
        catch (ClassNotFoundException e)
        {
            System.out.println(e);
        }
    }
}

Note: If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn’t find the class, loadClass() calls the method findClass() to find and load the class. The findClass() method searches for the class in the current ClassLoader if the class wasn’t found by the parent ClassLoader.

This article accurately reflects the updated understanding of Java ClassLoaders, including changes introduced from Java 9 onwards.



Similar Reads

Class forName(String, boolean, ClassLoader) method in Java with Examples
The forName(String, boolean, ClassLoader) method of java.lang.Class class is used to get the instance of this Class with the specified class name, using the specified class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax: public static Class&lt;T&gt; forName(String classNam
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
8 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg