How ClassLoader Loads Classes in Java
April 01, 2014
To load classes in java platform, java uses different Class loader and each class loader searches classes in a defined path. Here in this tutorial we are explaining three class loaders. First is boost strap class loader that loads boots strap classes, second is extension class loader that loads classes from ext directory of JRE. Now the next one is system class loader that loads class from classpath. Now read in more detail.
What are Bootstrap and Extension classes?
Bootstrap classes are those classes which creates java platform. The classes containing rt.jar and other jar are the Bootstrap classes. Bootstrap classes are loaded first in JVM by bootstrap class loader.
Extension classes and Extension mechanism
Java Extension classes resides in %JRE_HOME%/lib/ext
. Extension mechanism is a way to provide custom API to all applications running on the java platform. In this way extension classes will also be the part of java platform classes. Extension classes are loaded after bootstrap classes. Extension classes are loaded by extension class loader.
Hierarchy of ClassLoader
So there are three types of API to be loaded in JVM to run the java program.
a. Bootstrap classes
b. Extension classes
c. User classes
Find the class loader which loads the above API.
Bootstrap Class Loader loads bootstrap classes first in JVM.
Extension class loader loads extension classes and it runs after bootstrap class loader.
System class loader loads classes from the CLASSPATH defined by user. In the classpath, classes can be user defined classes, tools.jar API and user defined other API. System class loader loads classes after extension class loader.
So hierarchy of class loading is first bootstrap class loader then extension classloader and then system classloader.
Mechanism of Class Loading in Java
Now we will understand the mechanism of class loading. Bootstrap class is the parent of extension classloader and extension classloader is the parent of system classloader. When a class loader starts to load classes, first it says to its parent classloader to find the class. Suppose system classloader starts to load a class. So first it will say extension class loader to find the class and extension class loader will say bootstrap classloader to search the class. If bootstrap classloader finds the class in bootstrap classes then that class is loaded into JVM. Other
wise responsibility of loading the given class is returned to extension classloader. Extension classloader tries to find the class in ext directory, if found the class is loaded into JVM otherwise the responsibility of loading the given class returns to system classloader and system class loader tries to find the class in classpath and loads into JVM.