kamranzafar / JCL

Jar Class Loader, a configurable and dynamic custom classloader designed to create, manage and manipulate isolated Java classloaders in IoC frameworks and web applications.
http://kamranzafar.github.com/
579 stars 161 forks source link

Integration with Guice? #29

Closed mumrah closed 9 years ago

mumrah commented 9 years ago

Any idea how this would play with Guice?

mumrah commented 9 years ago

Bump?

mumrah commented 9 years ago

Answering my own question here. It's actually fairly straightforward to use this with Guice. Instead of using JclObjectFactory to create objects, you simply bind the classes loaded by JCL into Guice.

Suppose you have SomeInterface in the system classpath, and SomeImpl in a jar to be loaded by JCL.

JarClassLoader jcl = new JarClassLoader();
jcl.add("some.jar");
Class<SomeInterface> clazz = (Class<SomeInterface>)jcl.loadClass("SomeImpl");
Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(SomeInterface.class).to(clazz);
    }
});

SomeInterface something = injector.getInstance(SomeInterface.class); // This returns SomeImpl

The trick is that SomeInterface cannot be in "some.jar" (or Guice for that matter). This makes it a bit tricky to organize your dependencies, but you should be able to use a "provided" scope in your build tool to ensure some.jar (or a directory of jars) does not include classes that will be loaded by the main (non-JCL) classloader.

mumrah commented 9 years ago

I've made a sample project showing this in more detail here: https://github.com/mumrah/guice-jcl

kamranzafar commented 9 years ago

great stuff.. apologies for not replying to this thread earlier as I didn't get a chance to test jcl with guice. But your contribution is very helpful. Thanks