Java Classloader
What is Java ClassLoader?
We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled program and stores it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.
There are three types of built-in ClassLoader in Java:
- Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes
- Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
- System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
from JAVA 9
The Java run-time has the following built-in class loaders:
Bootstrap class loader. It is the virtual machine's built-in class loader, typically represented as null, and does not have a parent.
Platform class loader. All platform classes are visible to the platform class loader that can be used as the parent of a ClassLoader instance. Platform classes include Java SE platform APIs, their implementation classes and JDK-specific run-time classes that are defined by the platform class loader or its ancestors.
To allow for upgrading/overriding of modules defined to the platform class loader, and where upgraded modules read modules defined to class loaders other than the platform class loader and its ancestors, then the platform class loader may have to delegate to other class loaders, the application class loader for example. In other words, classes in named modules defined to class loaders other than the platform class loader and its ancestors may be visible to the platform class loader.
- System class loader. It is also known as application class loader and is distinct from the platform class loader. The system class loader is typically used to define classes on the application class path, module path, and JDK-specific tools. The platform class loader is a parent or an ancestor of the system class loader that all platform classes are visible to it.
How does Java ClassLoader Work?
When JVM requests for a class, it invokes loadClass function of the ClassLoader by passing the fully classified name of the Class. The loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.
- If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.
- If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.