[英]Import a Groovy script into another Groovy Script at Runtime
我有一個看起來像這樣(當前)的Groovy文件。
main.groovy
import org.packages.mystuff.JavaClassIAmUsing;
public class MyObject {
def rate(item){
def o = evaluate(new File (new File(getClass().protectionDomain.codeSource.location.path).parent),"CommonFunctions.groovy");
println o.whoami();
}
}
我有另一個groovy文件叫
CommonFunctions.groovy
def whoami() {return 'no body';}
我正在嘗試將CommonFunctions腳本包含在主腳本中,但是腳本的位置在構建時是未知的(即我不能硬編碼腳本中的絕對文件路徑或java進程的absoulte路徑相對於哪里腳本將被存儲)。
我所知道的是腳本將在一起或在相對於調用腳本的位置(比如子目錄)。
我試圖嘗試定位調用腳本位置,但我收到錯誤
No signature of method: MyObject.evaluate()
考慮到在運行時使用GroovyClassLoader.parseClass(File)方法訪問主腳本,我如何重新編寫此腳本。
我不確定你為什么要這樣做,我認為制作一類CommonsFunctions
可以更簡單,你可以正常實例化並在任何地方使用。
但是, 有可能實現你想要的; 有了Groovy,沒有那么多限制......
建議的解決方案有兩個問題:
MyObject
類中的getClass()自然地引用了MyObject
類,因此您嘗試查找腳本的位置將失敗。 您處於正確的軌道上,但您需要使用周圍的Script類來解析腳本位置。 evaluate
並不像你認為的那樣真正起作用。 evaluate
方法的結果是腳本的結果,而不是Script
類的實例。 解決這個問題的一種方法是將CommonFunction
的方法重寫為閉包屬性。 在評估腳本時,這些屬性將在shell Binding
對象中可用。 所以,通過這些重寫,你最終會得到這樣的結果:
main.groovy
class MyObject {
def scriptDir
def rate(item) {
def commonFunctionsScriptFile = new File(scriptDir, "CommonFunctions.groovy")
def binding = new Binding()
new GroovyShell(binding).evaluate(commonFunctionsScriptFile)
println binding.variables.whoami()
}
}
scriptFile = new File(getClass().protectionDomain.codeSource.location.path)
new MyObject(scriptDir: scriptFile.parentFile).rate(null)
這里,腳本文件位置在腳本中解析,而不是在內部類中解析。
CommonFunctions.groovy
whoami = { 'no body' }
在這里, whoami
不再是一個方法,而是一個將被添加到綁定中的閉包屬性。 確保不使用def
為此屬性添加前綴,因為它將是一個局部變量而不是添加到綁定對象的屬性。
這些重寫后的輸出是預期的: no body
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.