Search code examples
javaclassloaderdynamic-class-loaders

Java Class Loaders


Can anyone point me a good resource or explain me about the concept behind Class Loaders? I found the following resource on class loaders http://www.onjava.com/lpt/a/5586 but still no help. The following questions may look silly but trying to answer them always confuses me.

  • Why do developers write Custom class loaders, why not invoke a Bootstrap class loader to invoke your custom classes? What is the need to define custom class loaders?

  • Why there are so many varieties of class loaders? eg: Bootsrap, Comman, Catalina class loader etc.,

    Thanks in advance.


Solution

  • I found the following, valid reasons to create custom classloaders:

    1. You want to load a class from an unconventional source (For example, the bytecode for one class is stored in a database, across the network or carried as 0 and 1s by pidgeons - MessengerPidgeonClassLoader). There is some ClassLoader implementations already in the API for such cases, such as URLClassLoader.

    2. You need to define a different hierarchy to load classes. Default implementations of the ClassLoader delegate the search first to the parent, then they try to load the class themselves. Maybe you want a different hierarchy. This is the reason why OSGI and Eclipse have its own ClassLoaders as the Manifest .MF files define all types of weird hierarchy paths (buddy-classloading, for example). All Eclipse classloaders implement the BundleClassLoader interface and have some extra code to find resources within Eclipse Plugins.

    3. You need to do some modification to the bytecode. Maybe the bytecode is encrypted, and you will unencrypt it on the fly (Not that it helps, really, but has been tried). Maybe you want to "patch" the classes loaded on the fly (A la JDO bytecode enhancement).

    Using a different classloader than the System Classloader is required if you need to unload classes from memory, or to load classes than could change their definition at runtime. A typical case is an application that generates a class on the fly from an XML file, for example, and then tries to reload this class. Once a class is in the System Classloader, there is no way to unload it and have a new definition.