且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 创建 GroovyShell 对象并执行 Groovy 脚本 | 完整代码示例 )

更新时间:2022-09-20 23:31:17

文章目录

一、Groovy 类中调用 Groovy 脚本

1、创建 GroovyShell 对象并执行 Groovy 脚本

2、代码示例

二、完整代码示例

1、调用者 Groovy 脚本的类

2、被调用者 Groovy 脚本

3、执行结果





一、Groovy 类中调用 Groovy 脚本



1、创建 GroovyShell 对象并执行 Groovy 脚本


首先 , 创建 GroovyShell 对象 , 在构造函数中 , 需要传入 Binding 对象 ;


def shell = new GroovyShell(getClass().getClassLoader(), binding)

然后 , 设置要调用的 Groovy 脚本对应的 File 文件对象 ;


def file = new File("Script.groovy")


最后 , 调用 GroovyShell 对象的 evaluate 方法 , 执行 Groovy 脚本 ;


shell.evaluate(file)



2、代码示例


代码示例 :


class Test {
    void startScript() {
        // 注意这里创建 groovy.lang.Binding
        def binding = new Binding()
        // 设置 args 参数到 Binding 中的 variable 成员中
        binding.setVariable("args", ["arg0", "arg1"])
        // 执行 Groovy 脚本
        def shell = new GroovyShell(getClass().getClassLoader(), binding)
        def file = new File("Script.groovy")
        shell.evaluate(file)
    }
}
new Test().startScript()




二、完整代码示例



1、调用者 Groovy 脚本的类


class Test {
    void startScript() {
        // 注意这里创建 groovy.lang.Binding
        def binding = new Binding()
        // 设置 args 参数到 Binding 中的 variable 成员中
        binding.setVariable("args", ["arg0", "arg1"])
        // 执行 Groovy 脚本
        def shell = new GroovyShell(getClass().getClassLoader(), binding)
        def file = new File("Script.groovy")
        shell.evaluate(file)
    }
}
new Test().startScript()



2、被调用者 Groovy 脚本


/*
    下面的 age 和 age2 都是变量定义
    age 变量的作用域是 本地作用域
    age2 变量的作用域是 绑定作用域
    一个是私有变量 , 一个是共有变量
 */
// 打印参数
println args
def age = "18"
age2 = "16"
// 打印绑定作用域变量
println binding.variables
println "$age , $age2"
/*
    定义一个函数
    在下面的函数中 , 可以使用 绑定作用域变量
    不能使用 本地作用域变量
 */
void printAge() {
    println "$age2"
    //println "$age"
}
printAge()



3、执行结果


上面的两个 Groovy 脚本都在相同目录 ;


[arg0, arg1]
[args:[arg0, arg1], age2:16]
18 , 16
16