zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 参考 Script#evaluate 方法 | 创建 Binding 对象并设置 args 参数 )

方法对象 设置 创建 参数 脚本 调用 参考
2023-09-14 09:07:29 时间





一、Groovy 类中调用 Groovy 脚本




1、参考 Script#evaluate 方法分析 Groovy 类中调用 Groovy 脚本


可以参考 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);
    }
}

2、创建 Binding 对象并设置 args 参数


此处创建 GroovyShell 实例对象 涉及到传入 Binding 类型的参数 , 这个参数是 绑定作用域 变量 参数 ;

  • 在 Groovy 脚本中 , 该变量本身就被封装在 Script 类中 , 可以直接调用 Binding binding 成员 ;

  • 但是在 Groovy 类中 , 并没有该 Binding 成员变量 , 需要通过手动创建 Binding 实例对象 , 然后传入 GroovyShell 构造函数 ;

在 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"])