commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Craig McClanahan <craig...@gmail.com>
Subject Re: AW: AW: AW: AW: [proposal] avoiding jar version nightmares
Date Sun, 19 Dec 2004 23:16:41 GMT
On Sun, 19 Dec 2004 23:51:06 +0100, Daniel Florey <daniel.florey@web.de> 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: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message