chrisb chrisb - 1 year ago 142
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 )

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download