The Classloaders in Java dynamically load Java classes into the Java Virtual Machine. Usually classes are only loaded on demand.
By default, Java uses three class loaders, when JVM starts.
- Bootstrap classloader
- Extension classloader
- System classloader
Following figure shows the role of each ClassLoader:-
The ClassLoaders in Java works on 3 Principles:-
- Delegation – Forward request of class loading to the parent ClassLoader and only load the Class if the parent is not able to find or load the Class.
- Visibility – Allows child ClassLoaders to see all the Classes loaded by the parent ClassLoader. But parent ClassLoader cannot see the Classes loaded by the child ClassLoader.
- Uniqueness – Allows to load a Class exactly once, which is basically achieved by delegation and ensures that child ClassLoader does not reload the same Class already loaded by the parent ClassLoader.
Let us see a simple Java program to print the ClassLoader of the Class.
public class MyClass { public static void main(String[] args) { //Get the ClassLoader of the class MyClass ClassLoader classLoader = MyClass.class.getClassLoader(); System.out.println(classLoader); //Get the parent ClassLoader of classLoader ClassLoader parentClassLoader = classLoader.getParent(); System.out.println(parentClassLoader); //Get the super ClassLoader, This will return null as we are trying //to get the Bootstrap ClassLoader ClassLoader superClassLoader = parentClassLoader.getParent(); System.out.println(superClassLoader); //This will return null as we are trying to get the ClassLoader // of the core Java Runtime Class, which is Bootstrap ClassLoader ClassLoader stringClassLoader = String.class.getClassLoader(); System.out.println(stringClassLoader); } }
Running the above Class, produces the following output:-
sun.misc.Launcher$AppClassLoader@3f677737 sun.misc.Launcher$ExtClassLoader@21c3dc66 null null