Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

A class loader is an object that is responsible for loading classes. Further, class loaders load Java classes dynamically to the JVM (Java Virtual Machine) during runtime. They’re also part of the JRE (Java Runtime Environment). Therefore, the JVM doesn’t need to know about the underlying files or file systems to run Java programs thanks to class loaders.

Furthermore, the JVM doesn’t load these Java classes into memory all at once, but rather when an application requires them. This is where class loaders come into the picture. They’re responsible for loading classes into memory.

In this tutorial, we’ll talk about different types of built-in class loaders and how they work. Then we’ll introduce our custom implementation.

Further reading:

Understanding Memory Leaks in Java

Learn what memory leaks are in Java, how to recognize them at runtime, what causes them, and strategies for preventing them.

ClassNotFoundException vs NoClassDefFoundError

Learn about the differences between ClassNotFoundException and NoClassDefFoundError.

2. What Are the Functions of a Class Loader?

A class loader has two main functions:

  • Load Classes – Different built-in and custom class loaders load classes. We can extend the java.lang.ClassLoader abstract class to create class loader implementations
  • Locate Resources – A resource is some data such as a .class file, configuration information, or an image. We typically package resources with an application or library so that they are easy to locate

At the outset, class loaders don’t create objects for array classes. Instead,  the Java runtime creates them automatically as required. Therefore, when we use Class#getClassLoader() to find the class loader for an array class, it returns the class loader for its element type. Accordingly, an array class has no class loader if the element type is a primitive data type.

3. Types of Built-in Class Loaders

The Java run-time supports three built-in class loaders:

  • Bootstrap class loader – The virtual machine’s built-in class loader, is represented as null
  • Platform class loader – Loads the platform classes, which include the Java SE platform APIs, their implementation classes, and JDK-specific run-time classes. The platform class loader is the parent of the system class loader
  • System class loader – Also known as application class loader, loads classes on the application class path, module path, and JDK-specific tools

3.1. A Demo

Let’s start by learning how we can load different classes using various class loaders:

public void printClassLoaders() throws ClassNotFoundException {

    System.out.println("Platform Classloader:" 
      + ClassLoader.getPlatformClassLoader()); 

    System.out.println("System Classloader:" 
      + ClassLoader.getSystemClassLoader());

    System.out.println("Classloader of this class:"
      + PrintClassLoader.class.getClassLoader());

    System.out.println("Classloader of DriverManager:"
      + DriverManager.class.getClassLoader());

    System.out.println("Classloader of ArrayList:"
      + ArrayList.class.getClassLoader());
}

When executed, the above method prints:

Platform Classloader:jdk.internal.loader.ClassLoaders$PlatformClassLoader@5674cd4d
System Classloader:jdk.internal.loader.ClassLoaders$AppClassLoader@33909752
Classloader of this class:jdk.internal.loader.ClassLoaders$AppClassLoader@33909752
Classloader of DriverManager:jdk.internal.loader.ClassLoaders$PlatformClassLoader@5674cd4d
Classloader of ArrayList:null

As we can see, there are three different class loaders here: bootstrap (displayed as null), platform, and system.

The system class loader loads the class that contains the example method. Let’s remember that the system class loader loads our files in the classpath.

Next, the platform class loader loads the DriverManager class.

Finally, the bootstrap class loader loads the ArrayList class. A bootstrap or primordial class loader is the parent of all the others; however, it doesn’t have a parent.

However, we can see that for the ArrayList, it displays null in the output. This is because the bootstrap class loader is written in native code, not Java, so it doesn’t show up as a Java class. As a result, the behavior of the bootstrap class loader will differ across JVMs.

Now, let’s discuss each of these class loaders in more detail.

3.2. Bootstrap Class Loader

An instance of java.lang.ClassLoader loads Java classes. However, class loaders are classes themselves. So the question is, who loads the java.lang.ClassLoader itself? This is where the bootstrap or primordial class loader comes into play. It’s mainly responsible for loading JDK internal classes, typically rt.jar and other core libraries located in the $JAVA_HOME/jre/lib directory. Additionally, the Bootstrap class loader serves as the parent of all the other ClassLoader instances.

This bootstrap class loader is part of the core JVM and is written in native code, as pointed out in the above example. Different platforms might have different implementations of this particular class loader.

3.3. Platform Class Loader

The platform class loader is a child of the bootstrap class loader and takes care of loading the standard core Java classes so that they’re available to all applications running on the platform.

3.4. System Class Loader

The system or application class loader, on the other hand, takes care of loading all the application-level classes into the JVM. It loads files found in the classpath environment variable, -classpath, or -cp command line option. It’s also a child of the platform class loader.

4. How Does Class Loaders Work?

Class loaders are part of the Java Runtime Environment. When the JVM requests a class, the class loader tries to locate the class and load the class definition into the runtime using the fully qualified class name. The java.lang.ClassLoader.loadClass(String name, boolean resolve) method is responsible for loading the class definition into runtime using its binary name. This method is an overloaded method; it has a variant java.lang.ClassLoader.loadClass(String name) with different parameters. It performs an ordered search:

  1. It calls the findLoadedClass(String name) to check if the class has already been loaded. The method returns the class with the given binary name if the loader has already loaded the class. Otherwise, it returns null.
  2. It calls the loadClass(String) method on the parent class loader. Further, it uses the virtual machine’s built-in class loader if the parent is null.
  3. It calls the findClass(String) method to find the class.

As a result of the ordered search, if it doesn’t find the class and additionally we have set the resolve flag to true, it calls the resolveClass(Class) method on the resulting binary Class object.

As a result of the ordered search, if the class is not found, it throws java.lang.ClassNotFoundException.

Now, let’s examine three important features of class loaders.

4.1. Delegation Model

The delegation model means that the ClassLoader class delegates the search for a class or resource to its parent class loader before it tries to find the class or resource itself. The delegation model is hierarchical by default. The ClassLoader class supports concurrent loading of classes; therefore, it is parallel capable. Class loader implementations can register themselves at initialization time if they are to be parallel capable.

Class loaders follow the delegation model, where on being requested to find a class or resource, a ClassLoader instance will delegate the search of the class or resource to the parent class loader.

Let’s say we have a request to load an application class into the JVM. The system class loader first delegates the loading of that class to its parent platform class loader, which in turn delegates it to the bootstrap class loader.

Only if the bootstrap and then the platform class loader are unsuccessful in loading the class, does the system class loader try to load the class itself.

4.2. Unique Classes

As a consequence of the delegation model, it’s easy to ensure unique classes, as we always try to delegate upwards.

If the parent class loader isn’t able to find the class, only then will the current instance attempt to do so itself.

4.3. Visibility

In addition, child class loaders are visible to classes loaded by their parent class loaders.

For instance, classes loaded by the system class loader have visibility into classes loaded by the platform and bootstrap class loaders, but not vice-versa.

To illustrate this, if Class A is loaded by the application class loader, and class B is loaded by the platform class loader, then both A and B classes are visible as far as other classes loaded by the application class loader are concerned.

Class B, however, is the only class visible to other classes loaded by the platform class loader.

5. Custom ClassLoader

The built-in class loader is sufficient for most cases where the files are already in the file system.

However, in scenarios where we need to load classes out of the local hard drive or a network, we may need to make use of custom class loaders.

In this section, we’ll cover some other use cases for custom class loaders and demonstrate how to create one.

5.1. Custom Class Loaders Use-Cases

Custom class loaders are helpful for more than just loading the class during runtime. A few use cases might include:

  1. Helping to modify the existing bytecode, e.g. weaving agents
  2. Creating classes dynamically suited to the user’s needs, e.g. in JDBC, switching between different driver implementations is done through dynamic class loading.
  3. Implementing a class versioning mechanism while loading different bytecodes for classes with the same names and packages. This can be done either through a URL class loader (load jars via URLs) or custom class loaders.

Below are more concrete examples where custom class loaders might come in handy.

Browsers, for instance, use a custom class loader to load executable content from a website. A browser can load applets from different web pages using separate class loaders. The applet viewer, which is used to run applets, contains a ClassLoader that accesses a website on a remote server instead of looking in the local file system.

It then loads the raw bytecode files via HTTP, and turns them into classes inside the JVM. Even if these applets have the same name, they’re considered different components if loaded by different class loaders.

Now that we understand why custom class loaders are relevant, let’s implement a subclass of ClassLoader to extend and summarise the functionality of how the JVM loads classes.

5.2. Creating Our Custom Class Loader

For illustration purposes, let’s say we need to load classes from a file using a custom class loader.

We need to extend the ClassLoader class and override the findClass() method:

public class CustomClassLoader extends ClassLoader {

    @Override
    public Class findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassFromFile(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassFromFile(String fileName)  {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(
                fileName.replace('.', File.separatorChar) + ".class");
        byte[] buffer;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inputStream.read()) != -1 ) {
                byteStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = byteStream.toByteArray();
        return buffer;
    }
}

In the above example, we defined a custom class loader that extends the default class loader and loads a byte array from the specified file.

6. Understanding java.lang.ClassLoader

Let’s discuss a few essential methods from the java.lang.ClassLoader class to get a clearer picture of how it works.

6.1. The loadClass() Method

This method is responsible for loading the class given a name parameter. The name parameter refers to the fully qualified class name:

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

The Java Virtual Machine invokes the loadClass() method to resolve class references, setting resolve to true. However, it isn’t always necessary to resolve a class. If we only need to determine if the class exists or not, then we set the resolve parameter to false.

This method serves as an entry point for the class loader.

The default implementation of the method searches for classes in an order, already discussed.

6.2. The defineClass() Method

This method is responsible for the conversion of an array of bytes into an instance of a class. Before we use the class, we need to resolve it:

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

If the data doesn’t contain a valid class, it throws a ClassFormatError.

Also, we can’t override this method, since it’s marked as final.

6.3. The findClass() Method

This method finds the class with the fully qualified name as a parameter. We need to override this method in custom class loader implementations that follow the delegation model for loading classes:

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

In addition, loadClass() invokes this method if the parent class loader can’t find the requested class.

The default implementation throws a ClassNotFoundException if no parent of the class loader finds the class.

6.4. The getParent() Method

This method returns the parent class loader for delegation:

public final ClassLoader getParent()

Some implementations, like the one seen before in Section 4, use null to represent the bootstrap class loader.

6.5. The getResource() Method

This method tries to find a resource with the given name:

public URL getResource(String name)

It’ll first be delegated to the parent class loader for the resource. If the parent is null, the path of the class loader built into the virtual machine is searched.

If that fails, then the method will invoke findResource(String) to find the resource. The resource name specified as an input can be relative or absolute to the classpath.

It returns a URL object for reading the resource, or null if the resource can’t be found or the invoker doesn’t have adequate privileges to return the resource.

It’s important to note that Java loads resources from the classpath.

Finally, resource loading in Java is considered location-independent, as it doesn’t matter where the code is running as long as the environment is set to find the resources.

7. Context Class Loaders

In general, context class loaders provide an alternative method to the class-loading delegation scheme introduced in J2SE.

As we learned before, classloaders in a JVM follow a hierarchical model, such that every class loader has a single parent except for the bootstrap class loader.

However, sometimes when JVM core classes need to dynamically load classes or resources provided by application developers, we might encounter a problem.

For example, in JNDI, the core functionality is implemented by the bootstrap classes in rt.jar. But these JNDI classes may load JNDI providers implemented by independent vendors (deployed in the application classpath). This scenario calls for the bootstrap class loader (parent class loader) to load a class visible to the application loader (child class loader).

J2SE delegation doesn’t work here, and to get around this problem, we need to find alternative ways of class loading. This can be achieved using thread context loaders.

The java.lang.Thread class has a method, getContextClassLoader(), that returns the ContextClassLoader for the particular thread. The ContextClassLoader is provided by the creator of the thread when loading resources and classes. As of Java SE 9, threads in the fork/join common pool always return the system class loader as their thread context class loader.

8. Conclusion

Class loaders are essential to execute a Java program. In this article, we provided a good introduction to them.

We discussed the different types of class loaders, namely Bootstrap, Platform, and System class loaders. Bootstrap serves as a parent for all of them and is responsible for loading the JDK internal classes. Platform and system, on the other hand, load classes from the Java platform and classpath, respectively.

We also learned how class loaders work and examined some features, such as delegation, visibility, and uniqueness. Then we briefly explained how to create a custom class loader. Finally, we provided an introduction to Context class loaders.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)