Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load closure code from string in Groovy

is it possible to load a closure's code from a string (that may come from a file) in Groovy ?

like image 299
xain Avatar asked May 25 '11 18:05

xain


People also ask

How do I return a Groovy closure?

We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call() method or the implicit syntax with just the closure object followed by opening and closing parentheses (()).

What is -> in Groovy?

It is used to separate where you declare bindings for your closure from the actual code, eg: def myClosure = { x, y -> x + y } the part before -> declares that the closure has two arguments named x and y while the second part is the code of the closure.

How do you call a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.


2 Answers

Did you mean something like this?

groovy:000> sh = new GroovyShell()
===> groovy.lang.GroovyShell@1d6dba0a
groovy:000> closure = sh.evaluate("{it -> println it}")
===> Script1$_run_closure1@59c958af
groovy:000> closure(1)
1
===> null
groovy:000> [1,2,3,4].each { closure(it) }
1
2
3
4
===> [1, 2, 3, 4]
groovy:000> 
like image 147
Binil Thomas Avatar answered Oct 23 '22 12:10

Binil Thomas


This should work, not sure if it's the most elegant solution:

ClassLoader parent = getClass().getClassLoader()
GroovyClassLoader loader = new GroovyClassLoader(parent)
Class groovyClass = loader.parseClass("class ClosureHolder {def closures = [{ println 'hello world!' }]}")
def allTheClosures = groovyClass.newInstance()

allTheClosures.closures.each {
    it()
}

Just put your closures inside the list when reading them in.

like image 40
paradoxbomb Avatar answered Oct 23 '22 12:10

paradoxbomb