我有一个 groovy 脚本 createWidget.groovy:
import com.example.widget
Widget w = new Widget()
当我这样运行时,这个脚本运行得很好:
$ groovy -cp /path/to/widget.jar createWidget.groovy
但是,我想在脚本中硬编码类路径,这样用户就不需要知道它在哪里,所以我修改了 createWidget.groovy 如下(这是在 groovy 中修改类路径的方法之一):
this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL())
import com.example.widget
Widget w = new Widget()
但这总是会因导入时出现运行时错误而失败:无法解析类 com.example.widget
。
这看起来确实不正统,我认为您不能在导入之前弄乱 rootLoader 还是其他什么东西?
最佳答案
// 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();
关于java - 在groovy中动态加载jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219805/