Table of contents
1.
Introduction
2.
What is ClassLoader in Java?
3.
Types of Java Classloader 
3.1.
1. Bootstrap Classloader
3.2.
2. Extension Classloader
3.3.
3. System Classloader
4.
How Does Java Classloader Work?
4.1.
Java
5.
Principles of Functionality of a Java ClassLoader
5.1.
1. Delegation Model
5.2.
2. Visibility Principle
5.3.
3. Uniqueness Property
6.
Methods of Java Classloader
6.1.
1. loadClass()
6.2.
2. defineClass()
6.3.
3. findClass() 
6.4.
4. findLoadedClass()
6.5.
5. Class.forName()
7.
Example of ClassLoader in Java
7.1.
Java
8.
Frequently Asked Questions
8.1.
What is the use of Classloader in Java?
8.2.
What are the different types of ClassLoader?
8.3.
How to use ClassLoader in JUnit?
8.4.
How to check classes loaded in JVM?
8.5.
What is the difference between ClassLoader and JVM?
9.
Conclusion
Last Updated: Aug 30, 2024
Medium

ClassLoader in java

Author Nitika
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Java ClassLoader is a part of the Java Runtime Environment (JRE) that dynamically loads Java classes into the Java Virtual Machine (JVM) during program execution. It locates, loads, and initializes classes from various sources, such as the file system, network, or database, making them available for use by the Java application. In this article, we will discuss classloader in detail, like its types, principles, and methods.

java classloader

Read more, how to run java program

What is ClassLoader in Java?

The Class loaders in Java are responsible for dynamically loading Java classes into the Java Virtual Machine as part of the JRE(Java Runtime Environment). It belongs to the java.lang.package. When a Java Class is compiled, the JVM (Java Virtual Machine) creates a bytecode stored in a .class.file. Java Classes are loaded into the memory only when required, not all at once. Thus, the JRE calls the Java Classloaders to load the classes dynamically.

Types of Java Classloader 

Java Classloader is of three types:

  • Bootstrap Classloader
     
  • Extension Classloader
     
  • System Classloader

1. Bootstrap Classloader

Also called the Primordial ClassLoader, the Bootstrap ClassLoader is responsible for loading JDK class files from the  locations

.jre/lib/rt.jar

 

This type of Java classloader is the parent of all the other Classloaders.

In the ClassLoader Delegation Hierarchy, the bootstrap classloader is given the highest priority.

2. Extension Classloader

The Extension Classloader is the child of the above-discussed type of Java classloader and loads class files from the JDK Extension Library. It is responsible for loading class files from 

.jre/lib/ext 

 

directory or any additional directories as java.ext.dirs. 

3. System Classloader

Also known as an Application Classloader, it is responsible for loading the application type class file found in the CLASSPATH, -classpath or -cp command line option. It is a child of the Extension Classloader with the lowest priority in  the ClassLoader Delegation Hierarchy.

How Does Java Classloader Work?

Java Classloader is a part of the JRE. When the JVM calls for a class, the Java classloader attempts to locate it and load it into runtime using the fully qualified class name. It works in three principles: delegation, visibility, and uniqueness, which we will learn in the upcoming sections of this article.
The loadclass() method passes the name of the class and gets internally invoked when the program code requests the use of a class. findloaderclass() is called to prevent multiple classes from being loaded at the same time. If the class already exists, it delegates the request to the parent Classloader to start loading the class. And if the Classloader cannot locate its class in the database, it makes use of the java.net.URLClassLoader.findClass() method to find the classes in the system file. 

For example, the Bootstrap classloader first checks in rt.jar, and if the class is not present in it, it will move the request to the extension classloader, which searches in the directory jre/lib/ext.

If the required class files are not found, the findClass() gets invoked to fetch classes from the file system.

In simpler words,

  • Java Classloader checks if the class is loaded already.
     
  • If the class files are not loaded, it asks the parent class loader to load the class.
     
  • If the parent class loader cannot load the class, attempt to load it in this class loader.

Consider the following example,

  • Java

Java

public class Test
{
public static void main(String args[])
{ System.out.println("Hello Ninjas!!"); } }
You can also try this code with Online Java Compiler
Run Code

 

Compile and run the above code by using the command:

javac Test.java  
java -verbose:class Test

 

Output

Hello Ninjas!!

In the above example, we called a class called the Test class.

Also see,  Eclipse ide for Java Developers

Principles of Functionality of a Java ClassLoader

Java Classloader follows three principles of functionality. These are the rules that the Java Classloader follows. They are:

  • Delegation Model
     
  • Visibility Principle
     
  • Uniqueness Property
     

Let us learn more about them.

1. Delegation Model

Delegation Hierarchy Algorithm is used by the JVM and the Java Classloader to load the classes. The delegation model gives a set of operations for the classloader to follow. They are:

  • Classloader consistently follows the Delegation Hierarchy Model.
     
  • Whenever JVM comes across a class, it checks whether it is already loaded.
     
  • If the class is already loaded in the method area, the JVM proceeds with execution.
     
  • Suppose the class is not present in the method area. In that case, the JVM asks the Java Classloader Sub-System to load that particular class, and then the Classloader sub-system hands over the control to Application Classloader.
     
  • Application Classloader then delegates the request to Extension Classloader, and the Extension Classloader delegates the request to Bootstrap Classloader.
     
  • Bootstrap Classloader will search in Bootstrap classpath jre/lib/ext.It is loaded if the class is available; if not, the request is delegated to Extension Classloader.
     
  • Extension Classloader searches for the class in Extension Classpath jre/lib/ext. If the class is available, 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, it is loaded; if not, a ClassNotFoundException exception is generated.
     

2. Visibility Principle

It states that the classes loaded by the parent ClassLoader are visible to the child ClassLoader, but the vice-versa is invalid. For example, if the Extension ClassLoader loads a class, it and Application ClassLoader can see it, not the BootStrap ClassLoader. If BootStrap ClassLoader tries to load it now, it gives the ClassNotFOundException.

3. Uniqueness Property

It ensures there is no repetition of classes. Classes loaded by the parent ClassLoader are not loaded by the child ClassLoader. If the parent ClassLoader cannot find the class, the current instance will attempt to do so.

Methods of Java Classloader

Here are some important methods to be followed while loading a class

1. loadClass()

This method is used for loading a class that JVM references. The name of the class of type loadClass(String, boolean) is taken as the parameter.

Declaration:

public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

2. defineClass()

 It is used for defining an array as an instance of a class. The error ClassFormatError is thrown if it is invalid. This method can't be overridden as it is final. 

Declaration:

protected final Class<?> defineClass(String name, byte[] b, int off, int len) throws ClassFormatError

3. findClass() 

This method is used to find a specified class, not to load it.
Declaration:

protected Class<?> findClass(String name) throws ClassNotFoundException

4. findLoadedClass()

This method is used to verify whether the previous class referenced by JVM was loaded.
Declaration:

public ClassLoader getClassLoader()

5. Class.forName()

This method does load and initialises the class. It gives the option to choose any one Classloader. 

Declaration:

public static Class<?> forName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException


Also see, Java Ioexception

Example of ClassLoader in Java

The following example shows how classloader works in java. The example uses the java.lang.Class.getClassLoader() method.

  • Java

Java

package test;


import java.lang.*;


public class ClassDemo {


  public static void main(String[] args) {


     try {
     
        // returns the Class object associated with class


        Class cls = Class.forName("test.ClassDemo");


        // returns the Classloader object associated with Class


        ClassLoader cLoader = cls.getClassLoader();


        if (cLoader == null) {
           System.out.println("The default system class was used.");
        } else {
           // returns the classloader


           Class loaderClass = cLoader.getClass();


           System.out.println("Class associated with ClassLoader = " +
           loaderClass.getName());
        }
     } catch (ClassNotFoundException e) {
        System.out.println(e.toString());
     }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Class associated with ClassLoader = sun.misc.Launcher$AppClassLoader

 

Explanation:
In the above program, we used the getClassLoader() method to call a class object for the test.ClassDemo. if the cLoader == null, meaning that if the classloader is null, then the default java classloader was made use of. And if not, then the method is used and the name is printed.
The output of the program will be the name of the method used, which is the getClassLoader() and if the default method was used, then it will print the same.

Must Read, even number program in java

Frequently Asked Questions

What is the use of Classloader in Java?

The Class loaders in Java are responsible for dynamically loading Java classes into the Java Virtual Machine as part of the JRE(Java Runtime Environment). It belongs to the java.lang.package.  Java Classes are loaded into the memory only when required, not all at once.

What are the different types of ClassLoader?

There are mainly three different types of Java ClassLoaders namely: Bootstrap ClassLoader(also known as Primordial ClassLoader), Extension ClassLoader, and System ClassLoader(also known as Application ClassLoader).

How to use ClassLoader in JUnit?

To use ClassLoader in JUnit, it is possible indirectly by creating a custom ClassLoader. Then, you have to configure it in the @Before methods, and finally clean up in @After. Typically, you rely on the default class loading behaviour until and unless customization is necessary.

How to check classes loaded in JVM?

To check loaded classes in the JVM, you can use tools like jmap, JConsole, or VisualVM for graphical insights. Alternatively, programmatically access loaded classes using the Instrumentation API with a custom Java agent for more detailed analysis.

What is the difference between ClassLoader and JVM?

The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode, while the ClassLoader is a subsystem within the JVM responsible for loading class files into memory and making them available for execution by the JVM.

Conclusion

In this article, we discussed that the Java ClassLoader is a crucial component of the Java Runtime Environment (JRE) that enables dynamic loading of classes into the Java Virtual Machine (JVM) during program execution. It efficiently locates, loads, and initializes classes from various sources, ensuring that the required classes are available for the Java application to use.  The information on the different types of ClassLoaders, their principles, and the methods they use could be very useful for Java developers to create robust and flexible applications. 

Recommended Readings:

Live masterclass