【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 参考 Script#evaluate 方法 | 创建 Binding 对象并设置 args 参数 )
文章目錄
- 一、Groovy 類中調用 Groovy 腳本
- 1、參考 Script#evaluate 方法分析 Groovy 類中調用 Groovy 腳本
- 2、創(chuàng)建 Binding 對象并設置 args 參數(shù)
一、Groovy 類中調用 Groovy 腳本
1、參考 Script#evaluate 方法分析 Groovy 類中調用 Groovy 腳本
可以參考 groovy.lang.Script 類的 evaluate 方法 , 通過 GroovyShell 在類方法中調用 Groovy 腳本 ;
在 evaluate 方法中 , 首先創(chuàng)建 GroovyShell 實例對象 , 然后執(zhí)行該實例對象的 evaluate 方法 , 傳入要調用的 Groovy 腳本對應的 File 對象 ;
public abstract class Script extends GroovyObjectSupport {/*** 一個助手方法,允許使用此腳本綁定作為變量范圍動態(tài)計算groovy表達式** @param file 要執(zhí)行的 Groovy 腳本文件 */public Object evaluate(File file) throws CompilationFailedException, IOException {GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding);return shell.evaluate(file);} }2、創(chuàng)建 Binding 對象并設置 args 參數(shù)
此處創(chuàng)建 GroovyShell 實例對象 涉及到傳入 Binding 類型的參數(shù) , 這個參數(shù)是 綁定作用域 變量 參數(shù) ;
-
在 Groovy 腳本中 , 該變量本身就被封裝在 Script 類中 , 可以直接調用 Binding binding 成員 ;
-
但是在 Groovy 類中 , 并沒有該 Binding 成員變量 , 需要通過手動創(chuàng)建 Binding 實例對象 , 然后傳入 GroovyShell 構造函數(shù) ;
在 Binding 對象中的 Map variables 成員中 , 設置 args 參數(shù) , 作為調用 Groovy 腳本的執(zhí)行參數(shù) ;
首先 , 要在 Groovy 類方法中 , 創(chuàng)建 Binding 對象 ,
// 注意這里創(chuàng)建 groovy.lang.Bindingdef binding = new Binding()然后 , 調用 Binding 對象的 setVariable 方法 , 設置 args 執(zhí)行參數(shù) ;
// 設置 args 參數(shù)到 Binding 中的 variable 成員中binding.setVariable("args", ["arg0", "arg1"]) 《新程序員》:云原生和全面數(shù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 参考 Script#evaluate 方法 | 创建 Binding 对象并设置 args 参数 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】Groovy 脚本调用
- 下一篇: 【Groovy】Groovy 脚本调用