[英]How can I use wrapped Groovy shell inside the groovy script?
我有一個 Java 應用程序,我正在通過它執行 Groovy 腳本,當我的腳本再次具有使用 groovy shell 執行內部腳本的代碼時,就會出現問題。
像這樣的
import com.xx.WrappedGroovyShell
import java.lang.*
def scriptString = """
def test(str) {
str.toLowerCase() // This doesn't work as GString can't seem to be treated as a String
}
"""
try {
def script = WrappedGroovyShell.getInstance().getScript("Test1", scriptString)
def script2 = new GroovyShell().parse(scriptString)
def example = 1
def gstring = "OUR VALUE IS ${example}";
println script instanceof GroovyObject // Statement returning false
println script.test(gstring) // This throws an exception groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.runtime.GStringImpl.toLowerCase() is applicable for argument types: () values: []
println script2 instanceof GroovyObject // Statement returns true
println script2.test(gstring) //this one works
println "Success"
} catch (ex) {
println ex
}
return 0
WrappedGroovyShell.java 中的getScript方法非常簡單
public Script getScript(String scriptName, String scriptBody){
return new GroovyShell().parse(scriptBody);
}
如果有人讓我知道為什么有兩種不同的行為,我將不勝感激。
new GroovyShell()
創建一個新的 groovy 類加載器,parent = GroovyShell.class.getClassLoader()
如果 GString.class 對於父類加載器是未知的 - 那么它將再次加載。
由不同類加載器加載的兩個 GString 類不相等,這就是為什么您可能會遇到意外異常,例如“找不到參數 GString 的方法”或“無法將 GString 轉換為 GString”
這段代碼應該可以工作,因為它使用當前 groovy class 的類加載器
def scriptText='''
def test(str) {
str.toLowerCase()
}
'''
def gs = new GroovyShell(this.getClass().getClassLoader())
def script = gs.parse(scriptText)
def arg = "GSTRING ${123}"
println script.test(arg)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.