This example shows how to get the name of the class loader and parent class loader for the currently executing class. If you are not aware of the class loaders, please read our previous article about ClassLoader.
What is the ClassLoader ?
As its name implies, ClassLoader is a class that loads other classes. More scientific: The Classloader loads the bytecodes in its class to memory, so it can be used throughout your application. The ClassLoader is in the java.lang.ClassLoader package. Understanding the classloader is important for working on the server development or any product developments which is more often design the custom classloaders to load the classes. You would have come across the ClassNotFoundExecption many times while you are writing Java programming. Classloader is the culprit which causes this exception.
Lets look at the simple example for getting the current class loader and parent class loader.
GetClassLoaderExample.java
package javabeat.net.lang; /** * Get ClassLoader Example * * @author Krishna * */ public class GetClassLoaderExample { public static void main(String[] args) { Class<?> classVar = GetClassLoaderExample.class; //Print class loader name loaded this class System.out.println("Current Class Loader : " + classVar.getClassLoader().getClass().getName()); //Print parent class loader name for the current class loader System.out.println("Parent Class Loader : " + classVar.getClassLoader().getParent().getClass().getName()); } }
Output…
When you run the above code, you would get the output something like this. Note this will be depend on your Java environment.
Current Class Loader : sun.misc.Launcher$AppClassLoader Parent Class Loader : sun.misc.Launcher$ExtClassLoader