Load closure code from string in Groovy

前端 未结 3 2213
感情败类
感情败类 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条回答
  •  [愿得一人]
    2020-12-16 17:57

    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.

提交回复
热议问题