|
Re: Subduing CLASSPATH
|
Posted: Aug 25, 2006 8:18 AM
|
|
> > The context class loader can be used (no should be used in > > the current design of java class loading in the JVM) to > > aim class loading requests at specific class loaders. > > I curious how it determines the context inside a VM (not > necessarily a app server.) Query the stack?
Thread.currentThread().getContextClassLoader() is used by libraries to make sure that they load classes from the applications intended location. You can set the context classloader at any time using
Thread.currentThread().setContextClassLoader(ClassLoader) if you have permissions based on the active Policy.
If you want to download some code from a remote server, in your application, you might do the following to establish a new context class loader that provides access to your classes, and which delegates up the tree of existing loaders already active in the application.
URL[]urls = new URL[] { new URL("http://myserver/path/to/my.jar") };
// Create classloader, parenting it to the current // context class loader. URLClassLoader ld = new URLClassLoader( urls, Thread.currentThread().getContextClassLoader() );
Thread.currentThread().setContextClassLoader( ld );
To make class equality work 'better' for the average case, the delegation model in the JVM classloaders is look to the parent first. The preferred classloader, that I discussed earlier, would instead consult the preferred list, and if the class is preferred, it would load it from its jars (its a URLClassLoader subclass), instead of looking to the parent.
This preferring of particular classes helps manage intra jar dependencies much more readily than with the URLClassLoader, where you'd have to do some explicit loading, from inside your classes, to get exactly what you needed from the right classloader(s).
|
|