Search code examples
javajvmclassloader

How different classloaders resolve reference


If i create a custom class loader for say 3(A,B,C) classes of my Java app and redirect all other loading to default bootstrap class loader. Then according to JVM spec : "A reference to a class is consulted from current class loader and loaded (if necessary ) accordingly"

Now if i try to create object of class D(whose Class-Loader reference is bootstrap in "Class" class) from class A(whose Class-Loader reference is custom loader) , then custom-loader does not have any way to find path of D.class file (say i pick A,B,C from internet / some other place in which case , CLASSPATH is different in custom loader).

So how does this class finding problem would be resolved by JVM?


Solution

  • If you implement your custom classloader correctly there will be no problem. All classloaders have a parent. For a custom classloader it's typically the system class loader, the one that loads classes from Java class path. Typically classloader first of all offers (delegates) its parent to load a class and only if the parent fails then it tries to load the class. To make this happen custom classloader needs to implement findClass method and the delegation will be done automatically by ClassLoader.loadClass.

    Note that JVM has not only bootstrap class loader but a hierarchy of three class loaders

    bootstrap <- extension <- system