This a simple project in using a custom ClassLoader.
The simple idea is to embed GroovyClassLoader, and
so, be able to use all abilities of Groovy Language, but
it isn't enough. The target is to be able to expose
a normal ClassLoader and be able to unload the different
classes loaded and also all Groovy Environment, if needed.
To make a complete demonstration, i use a common
contract, the interface sample.module.RenderingModule,
and a simple Main class that host different tests.
The concrete implementation of the common contract are
expressed by groovy script (in reality simple java class).
The test uses generated class from groovy, thanks to
RenderingModule interface. As bonus I can add external
library, used by the script.
I've make direct use of ClassLoader but if you want a
more transparent use, you can adopt the strategy of
changing context classloader for current Thread
Thread.currentThread().setContextClassLoader(...);
To compile you need, in classpath, also groovy jar, but to execute
you only need it.fago.groovy and sample.module packages!
Run the different tests using the following parameters, if
you want to see the unloading effect, when resetting or destroying
the ClassLoader.
-verbose:class -ms2m -mx2m
We start setting where's Groovy binaries are
URL[] groovyLibs = new URL[] { ... };
than we create the ClassLoader
DelegatingClassLoader loader = new DelegatingClassLoader();
loader.init(groovyLibs);
thant we can add external libraries, as follow:
URL[] libs = new URL[] { ... };
loader.addURL(libs[0]);
we can now generate the concrete RenderingModule
Class<? extends RenderingModule> clz = loader.<RenderingModule> generateClassFromScript(script);
RenderingModule mod = clz.newInstance();
once generate, we can also load the generated class:
loader.loadClass("sample.module.SampleModule");
We can also reset the ClassLoader to purge loaded libraries and generated classes or to purge all the environment:
loader.resetPartially();
loader.resetTotally();
When we have ended with this ClassLoader, we can ensure a cleaned environment as follow:
loader.destroy();