Search code examples
javaclassloader

Java Classloader complexity


In trying to learn about Java class loaders from Wikipedia, I think I can see why they have the three major class loaders:

1) Bootstrap class loader
2) Extensions class loader
3) System class loader

They go on to say you can define your own classloader. I'm not sure I see the value in defining your own, but the following quote from Wikipedia really makes me wonder:

The most complex JAR hell problems arise in circumstances that take advantage of the full complexity of the classloading system. A Java program is not required to use only a single "flat" classloader, but instead may be composed of several (potentially very many) nested, cooperating classloaders. Classes loaded by different classloaders may interact in complex ways not fully comprehended by a developer, leading to errors or bugs that are difficult to analyze, explain, and resolve.


If it's so complex, why bother with it? Shouldn't the three already-defined classloaders be enough?

(And yes, for those curious, I did run into a ClassCastException that I didn't think should have happened, much like the graphic labelled Figure 2. Class identity crisis. I'm trying to understand the background is all.)


Solution

  • Certain use cases require custom classloaders. A few examples:

    • Dynamically adding new folders/jars to be loadable. (Without restarting the whole application).
    • Dynamically removing folder/jars from being loadable.
    • Runtime bytecode generation with javassist.
    • Multiple (actually used at the same time) versions of the same classes in the same application/jvm