Search

Dark theme | Light theme
Showing posts with label GroovyGoodness:Java. Show all posts
Showing posts with label GroovyGoodness:Java. Show all posts

February 23, 2020

Groovy Goodness: Lambda Default Parameter Value

Groovy 3 adds support for Java's lambda syntax expressions. This way we can write code in Groovy using lambda expressions just like in Java. But Groovy adds an additional feature and that is default parameter values for lambda expressions.

In the following example we use a default parameter value for a lambda expression.

// Groovy 3 supports Java's lambda syntax expressions.
def inc = n -> n + 1

assert inc(1) == 2


// But also adds default parameter values.
def multiplyBy = (n, factor = 2) -> n * factor

assert multiplyBy(1) == 2
assert multiplyBy(1, 10) == 10

Written with Groovy 3.0.1.

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) {        
        assertEquals(
            "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\"";
        assertEquals(
            "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()
        );
            
        assertTrue(
            "Invoke Eval.x() where the passed arguments name is x in the expression",
            (Boolean) Eval.x("mrhaki", "x.any { it =~ 'a' }")
        );
        
        assertTrue(
            "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.
        assertEquals(
            "Invoke Eval.xyz() where the passed arguments name is x, y and z in the expression",
            "GROOVYGROOVY", 
            Eval.xyz("groovy", 2, "toUpperCase", expression).toString()
        );
    }
}

November 17, 2009

Groovy Goodness: Running Groovy Scripts in Java with GroovyClassLoader

With the GroovyClassLoader we can load Groovy scripts and run them in Java code. First we must create a new GroovyClassLoader and then parse a Groovy script. The script can be in a file, string or inputstream. Once the script is parsed we have a Class and we can make a new instance of this class. We cast the instance to a GroovyObject instance, so we can use the invokeMethod() method to invoke methods in our Groovy script.

package com.mrhaki.blog;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

import java.io.File;
import java.io.IOException;

public class GroovyRun {
    public static void main(final String[] args) throws IllegalAccessException, InstantiationException, IOException {
        // Create GroovyClassLoader.
        final GroovyClassLoader classLoader = new GroovyClassLoader();
        
        // Create a String with Groovy code.
        final StringBuilder groovyScript = new StringBuilder();
        groovyScript.append("class Sample {");
        groovyScript.append("  String sayIt(name) { \"Groovy says: Cool $name!\" }");
        groovyScript.append("}");
        
        // Load string as Groovy script class.
        Class groovy = classLoader.parseClass(groovyScript.toString());
        GroovyObject groovyObj = (GroovyObject) groovy.newInstance();
        String output = groovyObj.invokeMethod("sayIt", new Object[] { "mrhaki" });
        assert "Groovy says: Cool mrhaki!".equals(output);
        
        // Load Groovy script file.
        groovy = classLoader.parseClass(new File("SampleScript.groovy"));
        groovyObj = (GroovyObject) groovy.newInstance();
        output = groovyObj.invokeMethod("scriptSays", new Object[] { "mrhaki", new Integer(2) });
        assert "Hello mrhaki, from Groovy. Hello mrhaki, from Groovy. ".equals(output);
    }
}
// File: SampleScript.groovy
class SampleScript {
    String scriptSays(name, num) { 
        "Hello $name, from Groovy. " * num
    }
}