Load closure code from string in Groovy

前端 未结 3 2216
感情败类
感情败类 2020-12-16 17:36

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

3条回答
  •  -上瘾入骨i
    2020-12-16 17:59

    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> 
    

提交回复
热议问题