2012-10-29 34 views
1

如果我跑GroovyScript這樣的:GroovyShell一個編譯字符串調用另一個

def gs=new GroovyShell() 
gs.setVariable('square',{x->x*x}) 
gs.evaluate("print square(10)") 

它工作得很好。問題是我想要「Square」函數也被編譯。我已經試過這樣:

def gs=new GroovyShell() 
gs.setVariable('square',gs.parse("{x->x*x}")) 
gs.evaluate("print square(10)") 

,但它不工作,我敢肯定,這是因爲通過gs.parse 返回的「腳本」對象不像個封閉 - 但我不不想改變第二個字符串的語法 - 如果我那樣做會有很多解決方案...

任何想法?

編輯: 寫完後,我意識到可以簡單地連接兩個字符串並解析它們一次,所以每次我想運行使用square()函數的腳本時,我都必須預先文字「def平方(x){x * x)\ n」給腳本...

我可以做到這一點,但它似乎有點flakey,所以我仍然對其他答案開放。

回答

1

非常接近!

您需要使用evaluate而不是解析得到一個封閉從GroovyShell回傳球作爲變量square:發現這有點酷

def gs=new GroovyShell() 
gs.setVariable('square', gs.evaluate('{ x -> x * x }')) 
gs.evaluate('print square(10)') 

,並得到了忘乎所以......你可以根據彼此關閉,如下所示:

def varMap = [ 
    square: '{ x -> x * x }', 
    pyth: '{ x, y -> Math.sqrt(square(x) + square(y)) }' 
] 

// Create a map of name->Closure set each into the shell 
// in turn, so later Closures can depend on earlier ones in 
// the list 
varMap = new GroovyShell().with { shell -> 
    varMap.collectEntries { name, func -> 
    // Get the closure 
    def fn = shell.evaluate(func) 
    // Set it into this current shell 
    shell.setVariable(name, fn) 
    // And return the Entry name->Closure 
    [ (name): fn ] 
    } 
} 

// Ok, this is what we want to run 
def command = 'println pyth(3, 4)' 

new GroovyShell().with { shell -> 
    // Set all the vars up 
    varMap.each { name, fn -> 
    shell.setVariable(name, fn) 
    } 
    // Then run the command 
    shell.evaluate(command) 
} 
+0

非常酷,謝謝。是的,這東西太有趣了。 –

相關問題