可以参考 groovy.lang.Script 类的 evaluate 方法 , 通过 GroovyShell 在类方法中调用 Groovy 脚本 ;
在 evaluate
方法中 , 首先创建 GroovyShell
实例对象 , 然后执行该实例对象的 evaluate
方法 , 传入要调用的 Groovy 脚本对应的 File 对象 ;
public abstract class Script extends GroovyObjectSupport {
/**
* 一个助手方法,允许使用此脚本绑定作为变量范围动态计算groovy表达式
*
* @param file 要执行的 Groovy 脚本文件
*/
public Object evaluate(File file) throws CompilationFailedException, IOException {
GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding);
return shell.evaluate(file);
}
}
此处创建 GroovyShell 实例对象 涉及到传入 Binding 类型的参数 , 这个参数是 绑定作用域 变量 参数 ;
在 Binding 对象中的 Map variables 成员中 , 设置 args 参数 , 作为调用 Groovy 脚本的执行参数 ;
首先 , 要在 Groovy 类方法中 , 创建 Binding 对象 ,
// 注意这里创建 groovy.lang.Binding
def binding = new Binding()
然后 , 调用 Binding 对象的 setVariable 方法 , 设置 args 执行参数 ;
// 设置 args 参数到 Binding 中的 variable 成员中
binding.setVariable("args", ["arg0", "arg1"])