在groovy中动态加载jar

rou*_*ble 4 java groovy classpath

我有一个groovy脚本createWidget.groovy:

 import com.example.widget

 Widget w = new Widget()
Run Code Online (Sandbox Code Playgroud)

当我像这样运行它时,这个脚本运行得很好:

$ groovy -cp /path/to/widget.jar createWidget.groovy
Run Code Online (Sandbox Code Playgroud)

但是,我想在脚本中硬编码类路径,以便用户不需要知道它在哪里,所以我修改了createWidget.groovy如下(这是在groovy中修改类路径的方法之一):

this.getClass().classLoader.rootLoader.addURL(new File("/path/to/widget.jar").toURL())

import com.example.widget

Widget w = new Widget()
Run Code Online (Sandbox Code Playgroud)

但是这总是在导入时出现运行时错误:unable to resolve class com.example.widget.

这看起来非常正统,我想你不能在导入之前搞乱rootLoader,还是别的什么?

Bae*_*hin 9

// 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();
Run Code Online (Sandbox Code Playgroud)


Pet*_*ser -1

Groovy 是一种编译语言,类名必须在编译时可解析。因此,在运行时添加 Jar 在这里是不够的。

( import 语句也是错误的,你必须追加.*or .Widget。但这并不能解决更深层次的问题。)