Tuesday, March 23, 2010

Class.forName (cslName) VS Thread.currentThread ().getContextClassLoader ().loadClass (clsname)

-- The thing to know here is that the context class loader is loading the class. All apps default, when first started, to the JVM application classloader as being the currentThread context loader. Often code like xerces, ejb based client code, etc will set a different classloader on the context thread. The main purpose is to allow higher up loaders in the hierarchy of a chain to "see" classes lower than it. Normall, any class loaded by a classloader can use any other class loaded by it or any of its parent (with regards to package names, visibility, and other java rules). But a parent loader can't "see" any child loaders classes. By using the thread context loader, a parent loader can be passed a reference to a child classloader of its own or any other classloader and ask that classloader to load classes for it, thus delegating in an unusual manner. It does, however, allow code loaded by the boot loader (rt.jar) to use your own code loaded by the app loader such that things like EJB calls are possible by rt.jar boot loaded classes. You may have to set the loader to your custom loader if you use custom loaders, otherwise its set to the application loader and by default any class loaded by the boot loader or extension loader can access the application loader ref through the context loader, allowing any code there to "see" any classes loaded by the app loader. This is how rt.jar EJB/rmi code can use your classes and reflection, even though they are loaded by a higher parent loader.

-- Sun Java Forum

No comments:

Post a Comment