tags:

views:

47

answers:

3

Hi,

In python, I can use eval() to execute user entered code in my program. Is there anything similar I can do in Groovy? I want to have a SWING UI textbox where the user enters a piece of code that I want to execute?

Thanks, Hari

A: 

Try this (but as usual with eval in any scripting language be careful about malicious code exeution):

evaluate("print new Date()")
Daff
I am trying to run a small piece of code in my custom grammar - will definitely check for malicious code.
Hari
+3  A: 

There are multiple ways of running Groovy (from both inside Java and Groovy):

http://groovy.codehaus.org/Embedding+Groovy

The quickest method however (for simple scripts), is probably to use the Eval class:

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

Which would let you do something like:

Eval.me( '2 + 2' )

See this page from more examples:

http://mrhaki.blogspot.com/2009/11/groovy-goodness-simple-evaluation-of.html

tim_yates
Thanks will try that!
Hari
+2  A: 

Yes, it is possible to dynamically evaluate code in Groovy by using Eval.x, Eval.xy, Eval.xyz or Eval.me. See the API doc for more details about these methods.

For example, you use Eval.me like this:

def a = "hello"
def b = "world" 
Eval.me(""" println "$a $b" """)
--> hello world

Also, see this blog post for some eval examples

bunting
You mean `Eval.xy( a, b, 'println "$x $y"' )` surely? ;-)
tim_yates
Nice catch, thanks. Changed from Eval.x to Eval.me. On the use of Eval.xy vs Eval.x - it's a matter of preference. In this case you can use either of them. Also, you can either use ' or """.
bunting