[英]groovy create closure programmatically
How to create closure
programmatically? 如何以编程方式创建
closure
?
I mean not like this 我的意思不是这样
def closure = { println "hello world" }
but more like this 但更像这样
Closure cl = new MethodClosure(this, "method")
....
and then call different methods of the closure to define body and etc. 然后调用不同的闭包方法来定义主体等。
Well, your example is not actually of creating a Closure programmatically because it basically requires parsing and compiling the method's source code into a Closure. 好吧,您的示例实际上不是以编程方式创建Closure的,因为它基本上需要解析并将方法的源代码编译为Closure。 The parsing being the problem.
解析是问题所在。 Creating a Closure programmatically would look similar to an implementation of a Groovy AST transformation;
以编程方式创建Closure类似于Groovy AST转换的实现; you'd be manipulating objects which represent low-level language constructs.
您将要处理代表低级语言构造的对象。 In pseudo-code... things like IfStatement, ClosureLiteral, MethodCall, etc. Then you'd compile this into objects;
用伪代码...如IfStatement,ClosureLiteral,MethodCall等,然后将其编译为对象; essentially by-passing source code parsing.
本质上绕过了源代码解析。 It's kind of like the difference between a String containing a query, and a query builder like Grail's GORM.
这有点像包含查询的字符串和查询生成器(如Grail的GORM)之间的区别。
However, Groovy does provide an easy way to do what you're looking for in your example using the Eval
class. 但是,Groovy确实提供了一种简单的方法来使用
Eval
类来完成您在示例中想要的事情。 Here's an example: 这是一个例子:
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.