我需要从SoapUI项目中的groovy脚本调用Jar中的一个方法。
由于缺乏管理权限,我无法将该jar放在SaopUI intall目录的“..bin/ext”文件夹中。
因此,剩下的唯一选项是在运行时加载jar并调用该方法。非常简单的方法。
我尝试了以下方法。
this.class.classLoader.rootLoader.addURL(new URL("file:///H://Foo-2//Foo.jar"));
def cls = Class.forName("test").newInstance();
cls.add()
这与rootLoader不一样
无效的
second approach .
def classLoader = ClassLoader.systemClassLoader
def newClassLoader = new URLClassLoader([new File("file:///H://Foo-2//Foo.jar")
.toString().toURL()] as URL[], classLoader)
def cls = Class.forName("test").newInstance();
这也不管用,它给了我
ClassNotFoundException类
.
我在这里呆了一天。看到这个后,甚至将类名改为小写
thread
.
编辑1
我试过这个
too
. 然后像这样更改我的代码。
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def classpathHacker = new com.eviware.soapui.support.ClasspathHacker ()
log.info "utils=" + groovyUtils
mystring = "file://H://Baz.jar"
com.eviware.soapui.support.ClasspathHacker.addURL( new URL(mystring) )
def cls = new bar() // how to call the static method add of `bar` class ?
log.info cls
我的Jar代码太简单了。给你
public class bar {
public static void main(String[] args) {
add();
}
public static void add(){
String path = "H:" + File.separator + "Groovy" + File.separator + "hi.txt";
File f = new File(path);
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我还有其他选择吗?我做错了什么?
解决了的。下面是最后一个Groovy脚本。
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def classpathHacker = new com.eviware.soapui.support.ClasspathHacker ()
path = groovyUtils.getProjectPath()
myfile = new java.io.File(path + "/Baz.jar")
mystring = "file://" + path + "/Baz.jar"
log.info "myfile=" + myfile
classpathHacker.addFile( myfile )
com.eviware.soapui.support.ClasspathHacker.addFile( myfile )
com.eviware.soapui.support.ClasspathHacker.addURL( new URL(mystring) )
def instance = this.class.classLoader.loadClass( 'bar', true, false )?.newInstance()
instance.add();