is it possible to load a closure's code from a string (that may come from a file) in Groovy ?
Asked
Active
Viewed 7,345 times
12
-
1If you're just looking at evaluating a string (the question is a little vague) this is very similar to http://stackoverflow.com/questions/3264014/equivalent-of-eval-in-groovy – Ted Naleid May 26 '11 at 02:54
-
Several solutions you can find here: https://stackoverflow.com/questions/36771508/how-to-dynamically-create-a-groovy-closure-from-a-string-in-java/49896047#49896047 – Naeel Maqsudov Apr 18 '18 at 09:39
3 Answers
16
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>

Binil Thomas
- 13,699
- 10
- 57
- 70
1
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.

paradoxbomb
- 414
- 5
- 8
-1
If you mean something like:
def cl = "{'hello'}" as Closure // fails, can't convert string to closure
No.
However, it appears evaluate() may be an option in this case: http://groovy.329449.n5.nabble.com/creating-closure-from-string-instance-td343089.html

virtualeyes
- 11,147
- 6
- 56
- 91