簡體   English   中英

groovy以編程方式創建閉包

[英]groovy create closure programmatically

如何以編程方式創建closure

我的意思不是這樣

def closure = { println "hello world" }

但更像這樣

Closure cl = new MethodClosure(this, "method")
....

然后調用不同的閉包方法來定義主體等。

好吧,您的示例實際上不是以編程方式創建Closure的,因為它基本上需要解析並將方法的源代碼編譯為Closure。 解析是問題所在。 以編程方式創建Closure類似於Groovy AST轉換的實現; 您將要處理代表低級語言構造的對象。 用偽代碼...如IfStatement,ClosureLiteral,MethodCall等,然后將其編譯為對象; 本質上繞過了源代碼解析。 這有點像包含查詢的字符串和查詢生成器(如Grail的GORM)之間的區別。

但是,Groovy確實提供了一種簡單的方法來使用Eval類來完成您在示例中想要的事情。 這是一個例子:

Closure closure = Eval.me("{ a, b -> a * b }")

assert closure instanceof Closure
assert closure(2, 3) == 6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM