[英]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?是否可以从 Groovy 中的字符串(可能来自文件)加载闭包代码?
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 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但是,在这种情况下,evaluate() 可能是一个选项: http://groovy.329449.n5.nabble.com/creating-closure-from-string-instance-td343089.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.