Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of eval() in Groovy

Tags:

groovy

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

like image 290
Hari Avatar asked Jul 16 '10 10:07

Hari


2 Answers

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

http://groovy-lang.org/integrating.html

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

http://groovy-lang.org/integrating.html#integ-eval

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

like image 187
tim_yates Avatar answered Nov 11 '22 19:11

tim_yates


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

like image 5
Kai Sternad Avatar answered Nov 11 '22 20:11

Kai Sternad