Reputation: 13395
How to create closure
programmatically?
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.
Upvotes: 1
Views: 783
Reputation: 9885
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. The parsing being the problem. Creating a Closure programmatically would look similar to an implementation of a Groovy AST transformation; 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; 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.
However, Groovy does provide an easy way to do what you're looking for in your example using the Eval
class. Here's an example:
Closure closure = Eval.me("{ a, b -> a * b }")
assert closure instanceof Closure
assert closure(2, 3) == 6
Upvotes: 1