November 25, 2009

Groovy Goodness: Simple Evaluation of Groovy Expressions in Java

We can run Groovy code from Java code in several ways. A very simple and easy way is to use the Eval class. The Eval class has five methods to execute simple Groovy expressions with zero to three arguments. All methods are static and the Groovy expression must be a String.


import java.util.*;
import groovy.util.Eval;
import junit.framework.*;
import static junit.framework.Assert.*;

public class EvalGroovyTest extends TestCase {
    public static void main(String[] args) {        
            "Invoke without arguments",
            "Hello from Groovy", 
  "def language = 'Groovy'; \"Hello from $language\";").toString()
        final Map values = new HashMap();
        values.put("name", "mrhaki");
        values.put("lang", "Groovy");
        String expression = "\"Hello $ from $params.lang\"";
            "Invoke with 2 arguments: first is name of object used by expression, second is object self",
            "Hello mrhaki from Groovy",
  "params", values, expression).toString()
            "Invoke Eval.x() where the passed arguments name is x in the expression",
            (Boolean) Eval.x("mrhaki", "x.any { it =~ 'a' }")
            "Invoke Eval.xy() where the passed arguments name is x and y in the expression",
            (Boolean) Eval.xy("mrhaki", "h", "x.any { it =~ y }")
        expression = "x.\"$z\"() * y";  // Unreadable expression to return x with the method z applied y times.
            "Invoke where the passed arguments name is x, y and z in the expression",
  "groovy", 2, "toUpperCase", expression).toString()