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.

package com.mrhaki.blog;

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 Eval.me() without arguments",
            "Hello from Groovy", 
            Eval.me("def language = 'Groovy'; \"Hello from $language\";").toString()
        final Map values = new HashMap();
        values.put("name", "mrhaki");
        values.put("lang", "Groovy");
        String expression = "\"Hello $params.name from $params.lang\"";
            "Invoke Eval.me() with 2 arguments: first is name of object used by expression, second is object self",
            "Hello mrhaki from Groovy",
            Eval.me("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 Eval.xyz() where the passed arguments name is x, y and z in the expression",
            Eval.xyz("groovy", 2, "toUpperCase", expression).toString()