使用GroovyShell解析类
我有一个groovy脚本,它需要在外部groovy脚本中的类内运行一个方法。 我知道如何在外部groovy脚本中运行方法:使用GroovyShell解析类,groovy,groovyshell,Groovy,Groovyshell,我有一个groovy脚本,它需要在外部groovy脚本中的类内运行一个方法。 我知道如何在外部groovy脚本中运行方法: new GroovyShell().parse( new File( 'foo.groovy' ) ).with { method() } 但是,如果该方法在一个类中呢?我试过了,但它给了我一个错误 new GroovyShell().parse( new File( 'foo.groovy' ) ).with { theclass.method()
new GroovyShell().parse( new File( 'foo.groovy' ) ).with {
method()
}
但是,如果该方法在一个类中呢?我试过了,但它给了我一个错误
new GroovyShell().parse( new File( 'foo.groovy' ) ).with {
theclass.method()
}
您可以使用Java反射创建位于另一个脚本中的类的新实例:
File sourceFile = new File("D:\\anoutherScript.groovy")
//here you have to update your classloader with external script
getClass().getClassLoader().addURL(sourceFile.toURI().toURL())
GroovyObject obj = Class.forName("ClassInAnotherObject").newInstance()
obj.doSth()
外部文件中的脚本如下所示:
class ClassInAnotherObject{
def doSth(){
}
}
但脚本文件中可能有更多的类,也可能有更多的指令和方法调用。就像普通的groovy脚本一样。您可以发布一个示例
foo.groovy
?无论如何,class
似乎需要实例化class.newInstance().method()