Tuesday, 6 November 2012

Adding to Classpath at Runtime

Sometimes you need to add a classpath to your application at runtime. I grappled with this problem when writing a maven plugin, with the abstract mojo class (You would think the mojo class from maven would be aware of the project classpaths, but nope). Anyway heres how to do it.
//get the current class loader
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();

//define paths you want on your classpath 
URL urls[] = new URL[]{
               new File("somedir/somedir2/somedir3").toURI().toURL(),
               new File("someOtherDir/someOtherDir2/someOtherDir3").toURI().toURL()

//create a new class loader with the new paths and the old classloader
ClassLoader newClassLoader = new URLClassLoader(urls, getClass().getClassLoader());

//set the new classloader as the classloader for this thread.

No comments:

Post a Comment