What is the role for a ClassLoader in Java?

Last updated on Nov 27,2019 7.7K Views

What is the role for a ClassLoader in Java?

edureka.co

While working in Java, we often use a large number of classes. These Java classes are not loaded all at once in the memory, instead, they are loaded when required by an application. This is where Java ClassLoaders come into the picture. So in this article, I will discuss how to use the ClassLoader in Java along with examples.

The following topics will be covered in this article:

  1. What is ClassLoader?
  2. Types of ClassLoader
  3. Principles of ClassLoader
  4. Methods of ClassLoader
  5. Custom ClassLoader

Let us get started!

What is ClassLoader in Java?

ClassLoader in Java is called by the Java Runtime Environment to dynamically load the classes whenever required by the application in the Java Virtual Machine. Since ClassLoaders are a part of the Java Runtime Environment, the Java Virtual Machine will not have any idea about the underlying files and files systems.

Now, let us understand the different types of built-in ClassLoaders in Java.

Types of ClassLoader in Java

The different types of ClassLoaders in Java are as follows:

Let us discuss each one of them one by one.

Extension ClassLoader

As the name suggests the Extension ClassLoader loads the extensions of the core Java classes from the JDK Extension library. It is a child of the Bootstrap ClassLoader and loads the extensions from the JRE/lib/text directory or any other directory specified in the java.ext.dirs system property.

Application or System ClassLoader

The Application or the System ClassLoader is a child of the Extension ClassLoader. This type of ClassLoader loads all the application level classes found in the -cp command-line option or int the CLASSPATH environment variable.

Bootstrap ClassLoader

As we all know that Java Classes are loaded by an instance of  java.lang.ClassLoade. But, since ClassLoaders are classes, the Bootstrap ClassLoader is responsible to load the JDK internal classes. BootStrap ClassLoader is a machine code that starts the operation when JVM calls it and loads the classes from rt.jar. So, you can understand that the Bootstrap ClassLoader serves has no parent ClassLoader and is thus known as Primordial ClassLoader.

Note: The priority of Bootstrap is higher than Extension, and the priority given to the Extension ClassLoader is higher than Application ClassLoader. Refer to the image below:

Next in this article, let us understand the principles on which the ClassLoader works.

Principles of ClassLoader in Java

The set of rules based on which the Java ClassLoader works are the following three principles:

Let us understand each one of them.

Uniqueness Property

This property ensures that there is no repetition of classes and all the classes are unique. The uniqueness property also makes sure that classes are loaded by the parent ClassLoader are not loaded by the child ClassLoader. In a scenario, where the parent ClassLoader cannot find the class, then the current instance will attempt to do it by itself.

Delegation Model

ClassLoader in Java work based on the set of operations given by the Delegation Model. So, whenever a request is generated to find a class or a resource, then a ClassLoader instance will delegate the search of the class or the resource to the parent ClassLoader.

The set of operations based on which the ClassLoader works are as follows:

Refer to the image below.

Visibility Principle

According to this principle, the children’s classes are visible to the classes loaded by its parent ClassLoaders, but the vice versa isn’t true. So, the classes loaded by the Application ClassLoader have visibility into the classes loaded by the Extension and Bootstrap ClassLoader.

For example, if we have two classes: A & B, assume that class A is loaded by the Application ClassLoader and class B is loaded by the Extensions ClassLoader. Here, classes A and B are visible to all those classes loaded by the Application ClassLoader, but class B is visible to only those classes loaded by the Extension ClassLoader.

Also, if you try to load these classes using the Bootstrap ClassLoader, you will see the  java.lang.ClassNotFoundException. exception.

Alright, now that you know the types of ClassLoaders and the principles behind it, let us look into a few important methods from the java.lang.ClassLoader class.

Methods of ClassLoader in Java

Few essential methods of ClassLoader are as follows:

loadClass(String name, boolean resolve)

This method is the entry point of the ClassLoader and is used to load the class referenced by the JVM. It takes the name of the class as a parameter. The JVM invokes the loadClass() method to resolve the class references by setting the boolean value to true. Only if we need to determine if the class exists or not, the boolean parameter is set to false.

Declaration:

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

defineClass()

A final method used to define an array of bytes as an instance of a class. In case the class is invalid then, it throws a ClassFormatError.

Declaration:

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

findClass(String name)

The findClass method is used to find the specified class. So, it just finds the class with a fully qualified name as a parameter but does not load the class. The loadClass() method invokes this method if the parent ClassLoader cannot find the requested class. Also, if no parent of the ClassLoader finds the class the default implementation throws a ClassNotFoundException.

Declaration:

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

Class.forName(String name, boolean initialize, ClassLoader loader)

This method is used to load and initialize the class. It gives an option to choose any of the ClassLoaders and incase the ClassLoader parameter is NULL, then automatically the Bootstrap ClassLoader is used.

Declaration:

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

getParent()

The getParent method is used to return the parent ClassLoader for delegation.

Declaration:

public final ClassLoader getParent()

getResource()

As the name suggests, the getResource() method tried to find a resource with the given name. It will initially delegate the request to the parent ClassLoader for the resource. In case the parent is null, then the path of ClassLoader built into the JVM is searched. Now, if this fails, then the method will invoke the findResource(String) to find the resource, where the resource name is specified as an input that can be either the absolute or relative classpath. Then, it returns a URL object for reading the resource or returns a null value if the resource does not have adequate privileges to return the resource or is not found.

Declaration:

public URL getResource(String name)

Next, in this article on ClassLoader in Java, let us understand the Custom ClassLoader.

Custom ClassLoader in Java

The built-in ClassLoaders will take care of most of the cases where the files are already in the file system, but if you want to load the classes out of the local hard drive then you need to make use of custom ClassLoaders.

Create Custom ClassLoader

To create a custom ClassLoader, you need to extend the ClassLoader class and override the findClass() method:

Example: Let us create a custom ClassLoader which extends the default ClassLoader and loads a byte array from the specified file. Refer to the code below.

package edureka;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class Sample extends ClassLoader {
	 
    @Override
    public Class findClass(String samplename) throws ClassNotFoundException {
        byte[] b = customLoadClassFromFile(samplename);
        return defineClass(samplename, b, 0, b.length);
    }
 
    private byte[] customLoadClassFromFile(String demofilename)  {
        InputStream inStream = getClass().getClassLoader().getResourceAsStream(
        		demofilename.replace('.', File.separatorChar) + ".class");
        byte[] buffer;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inStream.read()) != -1 ) {
                bStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = bStream.toByteArray();
        return buffer;
    }
}

With this, we come to an end to this article on ClassLoader in Java. I hope you understood what are ClassLoaders in Java, its methods, the different types of ClassLoaders, etc.

If you found this article on “ClassLoader in Java”, check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this “ClassLoader in Java and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR A Comprehensive UI/UX Design Tutorial