title: Dynamically load jar in groovy
body: <p>I have a groovy script createWidget.groovy:</p>
  
  <pre><code> import com.example.widget
  
   Widget w = new Widget()
  </code></pre>
  
  <p>This script runs great when I run it like this:</p>
  
  <pre><code>$ groovy -cp /path/to/widget.jar createWidget.groovy
  </code></pre>
  
  <p>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):</p>
  
  <pre><code>this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL())
  
  import com.example.widget
  
  Widget w = new Widget()
  </code></pre>
  
  <p>But this always fails with a runtime error on the import: <code>unable to resolve class com.example.widget</code>.</p>
  
  <p>This does look unorthodox and I am thinking you can't mess with the rootLoader prior to an import or is it something else?</p>