On Sun, 19 Dec 2004 23:51:06 +0100, Daniel Florey <[EMAIL PROTECTED]> wrote:
> 
> Simple example:
> If you have two libraries:
> Library A using component-1.x
> Library B using component-2.x
> Both libraries provide some servlets that need to live in the same webapp
> and get initialized at startup.

> How to make this work (for users with average java knowledge)?
> This is a simple example, but I could give you many others where libraries
> depend on each other and need to share the same classloader. So your
> proposal won't work.

Making this accessible to a Java developer with "average" knowledge
sounds like something a good commons package could deal with :-).  But
the basic outline of setting up the class loaders would go something
like this (the key class is java.net.URLClassLoader):

    // First, set up URLs for the dependencies of library A (easiest might
    // be to use "file:" URLs to the JAR files in a directory or something)
    URL urlsA[] = ... list of URLs for library A and its dependencies ...

    // Next, get a reference to the webapp class loader
    ClassLoader parentA = Thread.currentThread().getContextClassLoader();

    // Now, create a new child class loader for library A, making
    // it a child of the webapp class loader so classes within the
    // library can see everything in your webapp
    ClassLoader clA = new URLClassLoader(urlsA, parentA);

and the same sort of thing for library B.  (NOTE - you'll need to add
some appropriate exception handling in these code examples ... they
are just an outline)

Now, the trick is gaining access to objects provided by those
libraries ... you can't just say "new Foo()" -- for an instance of
class Foo from library A -- any more because that will only search in
the webapp's class loader.  Instead, you need something like:

    Class fooClass = clA.loadClass("com.libraryA.Foo");
    Foo instance = (Foo) fooClass.newInstance();

You'd probably be well served to set up convenience factory methods
for this sort of stuff if you need to do it a lot.

> 
> Daniel
> 

Craig

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to