【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 创建 GroovyShell 对象并执行 Groovy 脚本 | 完整代码示例 )
生活随笔
收集整理的这篇文章主要介绍了
【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 创建 GroovyShell 对象并执行 Groovy 脚本 | 完整代码示例 )
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 一、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.Bindingdef 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.Bindingdef 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 argsdef age = "18" age2 = "16"// 打印绑定作用域变量 println binding.variablesprintln "$age , $age2"/*定义一个函数在下面的函数中 , 可以使用 绑定作用域变量不能使用 本地作用域变量*/ void printAge() {println "$age2"//println "$age" }printAge()
3、执行结果
上面的两个 Groovy 脚本都在相同目录 ;
[arg0, arg1] [args:[arg0, arg1], age2:16] 18 , 16 16总结
以上是生活随笔为你收集整理的【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 创建 GroovyShell 对象并执行 Groovy 脚本 | 完整代码示例 )的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【Groovy】Groovy 脚本调用
- 下一篇: 【错误记录】Groovy工程中的文件查找