How to know which class is getting loaded by which class Loader in java?

1.3k Views Asked by At

Recently i was asked by a computer science professional to describe about the class loaders in Java. I explained him about 3 class loaders namely "BootStrap CL","Extension CL" and "Application CL", i also explained to him about "Deligation Algorithm". Next he asked me to prove it, can anyone give me a code to practically see the Classloaders in Execution?

1

There are 1 best solutions below

5
On

There are a few ways you could go about this:

  1. Show that different classes have different ClassLoader objects. For example, YourMainClass.class.getClassLoader() might be a sun.misc.Launcher$AppClassLoader, while System.class.getClassLoader() is null (as are other system classes). Here is a quick test:

    • Class from a JAR: sun.misc.Launcher$AppClassLoader@2a139a55
    • Main class: sun.misc.Launcher$AppClassLoader@2a139a55
    • java.lang.System's classloader: null
    • System class loader: sun.misc.Launcher$AppClassLoader@2a139a55
    • System class loader's parent: sun.misc.Launcher$ExtClassLoader@4aa298b7
    • Main class's classloader's parent: sun.misc.Launcher$ExtClassLoader@4aa298b7
    • Jar class loader's parent: sun.misc.Launcher$ExtClassLoader@4aa298b7

    The parent class loaders are used in the following way:

    1. A classloader recieves a request to load a class. If it already has it loaded, it returns it.
    2. That classloader first asks its parent to load it. If the parent cannot load it, then that classloader itself loads and returns it.
  2. Show the OpenJDK source, and its multiple ClassLoaders.

  3. Describe an application where this occurs in the real world. You could talk about scripting engines that define classes at runtime, servlet containers, certain build systems, etc, etc.