tags:

views:

312

answers:

2

In Python I can execute arbitrary code using exec(string). How can I do this in Groovy? I'd like the code to execute in the context of my currently running application, not as if I were using the Groovy shell.

+3  A: 

To execute a command-line program dynamically in Groovy:

"cmdstring".execute().text

You can also execute some Groovy code wrapped in a String with:

def myGroovyCode = 'println "hi"'
Eval.me(myGroovyCode) //prints hi

See http://groovy.codehaus.org/api/groovy/util/Eval.html

Eric Wendelin
This doesn't appear to work, I want to execute actual code, not a command line program.
Jared
Sorry I must have been on crack or something. You now have a real answer :)
Eric Wendelin
A: 

You can also pass in your current context parameters via the binding mechanism to the Groovy Shell.

def myname = 'Inigo Montoya'
def binding = new Binding( [ myname:myname ] )
new GroovyShell( binding ).evaluate( 'println "My Name is " + myname' )
tomas