问题描述
我有一个时髦的脚本createWidget.groovy:
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
但是,我想对脚本中的类路径进行硬编码,以便用户无需知道它在哪里,所以我按如下方式修改了createWidget.groovy(这是在groovy中修改类路径的方法之一):/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):
this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL())
import com.example.widget
Widget w = new Widget()
但这总是失败,并在导入时出现运行时错误:无法解析类com.example.widget
.
But this always fails with a runtime error on the import: unable to resolve class com.example.widget
.
这看上去确实是非传统的,我认为您在导入之前不能与rootLoader发生冲突,还是其他东西?
This does look unorthodox and I am thinking you can't mess with the rootLoader prior to an import or is it something else?
推荐答案
// 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();
这篇关于在Groovy中动态加载jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!