2014-03-06 26 views
2

我有一個腳本和實用程序方法,我想從我的其他腳本訪問。Groovy使方法從一個腳本可見到另一個腳本

我打開我的腳本這樣在我的Java代碼

static { 
    GroovyShell shell = new GroovyShell(); 
    //This is the script that has the utility 
    groovyUtils = shell.parse(new InputStreamReader(MyJavaClass.class.getResourceAsStream("scripts/json/MyUtils.groovy"))); 
    //This is the script that does thing 
    groovyScript = shell.parse(new InputStreamReader(MyJavaClass.class.getResourceAsStream("scripts/json/MyScript.groovy"))); 
} 

我想從MyUtils.groovy公開的方法是在MyScript.groovy(以及將來在其他腳本)

回答

2

有可用你可以通過多種方式實現這一點。

你說的是方法,所以我猜你在MyUtils.groovy有個班。 在這種情況下,您可以指定一個Binding,例如,

def myUtils = new MyUtils() 
def binding= new Binding([ method1: myUtils.&method1 ]) 
def shell= new GroovyShell(binding) 

shell.evaluate(new File("scripts/json/MyScript.groovy")) 

在上面,你可以參考在你的腳本method1,你最終會調用它myUtils實例。

另一種解決方案是指定一個腳本基類,例如,

def configuration = new CompilerConfiguration() 
configuration.setScriptBaseClass('MyUtils.groovy') 
def shell = new GroovyShell(this.class.classLoader, new Binding(), configuration) 

MyUtils類必須然後延伸Script;它的所有方法在您使用shell解析的腳本中都可用。


基本上有多種如何嵌入/運行Groovy的方法。這些在設計DSL時經常被討論。你可以看看例如here,如果您以前沒有搜索過它。

+0

這也是我在Google/Stackoverflow上搜索得到的結果,但它並不適用於我,因爲1.我的腳本位於classpath中,而且我正在使用Java創建GroovyShell,而不是groovy。 我現在有一個臨時解決方案是從我的腳本加載文本,然後執行腳本myScript = shell.parse(textFromUtils + System.lineSeparator()+ textFromMyScript);' –

+0

@NicolasMartel *我的腳本在類路徑*這應該沒有效果,只需使用不同的輸入法。 *我正在用Java創建我的GroovyShell * - 這也應該沒有區別;只是刪除我使用的所有語法糖。 – emesx

+0

如何在Java中執行'new Binding([method1:myUtils。&method1])'? Groovy仍然有點新,所以我不完全確定這會轉化爲什麼 –

相關問題