Wednesday, 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()


diƤtpillen said...

I can run Groovy code from Java code in several ways.

blog said...

Any idea how long Eval has been around? Just curious. I wrote some code a while ago where it would have been useful, but I'm not sure it existed yet.

By the way, I think in the expression on line 12, you meant to set a value for the language variable - something like this:
"def language = 'Groovy'; \"Hello from $language\";"

--Matt (the editor)

mrhaki said...

@blog: Eval has been around for a very long time. And thank you for finding the missing assignment to the language variable in line 12.

Post a Comment