Dynamically load jar in groovy

classpath, groovy, java

Solution

// Use the groovy script's classLoader to add the jar file at runtime.
this.class.classLoader.rootLoader.addURL(new URL("/path/to/widget.jar"));

// Note: if widget.jar file is located in your local machine, use following:
// def localFile = new File("/path/tolocal/widget.jar");
// this.class.classLoader.rootLoader.addURL(localFile.toURI().toURL());

// Then, use Class.forName to load the class.
def cls = Class.forName("com.example.widget").newInstance();

Problem

I have a groovy script createWidget.groovy: ``` import com.example.widget Widget w = new Widget() ``` This script runs great when I run it like this: ``` $ groovy -cp /path/to/widget.jar createWidget.groovy ``` But, I wanted to hardcode the classpath within the script, so that users do not need to know where it is, so I modified createWidget.groovy as follows (which is one of the ways to modify classpath in groovy): ``` this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL()) import com.example.widget Widget w = new Widget() ``` But this always fails with a runtime error on the import: `unable to resolve class com.example.widget`. This does look unorthodox and I am thinking you can't mess with the rootLoader prior to an import or is it something else?

Original source