is it possible to load a closure's code from a string (that may come from a file) in Groovy ?
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 (()).
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With