chrisb chrisb - 9 months ago 40
Groovy Question

How do I compile a groovy user entered script at runtime

I want to compile and execute a piece of Groovy that the user types in (in a DSL) at runtime. Is this possible in Groovy? And if so what's the best way to do it?

Answer Source

You can use the GroovyClassLoader:

def userScript = '''
  (1..5).each {
    println 'X' * it
  }
'''

Class c = new GroovyClassLoader().parseClass( userScript )
c.newInstance().run()

Or you can use any of the other methods in the documentation for integrating Groovy.