java - Dynamically load jar in groovy -
i have groovy script createwidget.groovy:
import com.example.widget widget w = new widget()
this script runs great when run this:
$ groovy -cp /path/to/widget.jar createwidget.groovy
but, wanted hardcode classpath within script, users not need know is, modified createwidget.groovy follows (which 1 of ways 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 fails runtime error on import: unable resolve class com.example.widget
.
this unorthodox , thinking can't mess rootloader prior import or else?
// use groovy script's classloader add jar file @ runtime. this.class.classloader.rootloader.addurl(new url("/path/to/widget.jar")); // note: if widget.jar file located in local machine, use following: // def localfile = new file("/path/tolocal/widget.jar"); // this.class.classloader.rootloader.addurl(localfile.touri().tourl()); // then, use class.forname load class. def cls = class.forname("com.example.widget").newinstance();