Thread Context Class Loader
It's also possible to try to resolve class loading problems by using the Java Thread API to obtain a class loader
programmatically. Section 6.2.4.8 of the J2EE 1.3 specification requires all J2EE containers to support the use
of the getContextClassLoader() method on java.util.Thread.
The J2EE specification isn't entirely clear regarding context class loading. However, the intent appears to be
to allow portable classes, such as value objects, to load application classes in whatever container (such as
EJB or web container) they may run in. In practice, the context class loader appears to be in the context of the
current container. To clarify this behavior, let's consider the effect of the following two calls, made by a helper
class that is loaded by the EJB class loader but used in both EJBs and classes running in the web container:
o Class.forName (classname): Will use the class loader of the helper class: in this case, the EJB class
loader. This means that, if the EJB class loader is the parent of the WAR class loader, the helper will
never be able to load classes in the WAR by name.
o Class.forName(classname, true, Thread.currentThread().getContextClassLoader()):
Wi l l use the current container's class loader. This means that the helper will behave differently
wherever it is running. If the EJB class loader is the parent of the WAR class loader, when the helper
is used in the EJB container, it will only be able to load EJB classes and classes loaded by higher class
loaders. If the helper is used in the WAR, it will be able to load WAR classes as well.
Many frameworks, such as Web Work, use this approach to avoid problems caused by hierarchical class loading.
However, it's not usually required in application code, which should normally only load classes by name using an
abstraction layer that should conceal any use of the context class loader.