Embedding Groovy in Java

0. Create some space where you can test everything

mkdir ~/groovy_and_java
cd ~/groovy_and_java

1. Download most recent version of Groovy

curl "http://dist.groovy.codehaus.org/distributions \
/groovy-binary-2.0.4.zip" -o groovy-binary-2.0.4.zip
unzip groovy-binary-2.0.4.zip

2. Create space for sample code

mkdir SampleCode
cd SampleCode

3. Create two files

SimpleGroovyCall.java

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

import java.io.File;

public class SimpleGroovyCall {

  public static void main(String[] args) {
    GroovyClassLoader loader = new GroovyClassLoader();
    GroovyObject groovyObj = null;
    try {
      Class groovyClass =
        loader.parseClass(new File("SimpleGroovyCode.groovy"));
      groovyObj = (GroovyObject) groovyClass.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    Object[] invokeArgs = {};

    System.out.println(
      groovyObj.invokeMethod("simple", invokeArgs));
    }
}

SimpleGroovyCode.groovy

def simple() {
    return "This is a simple call"
}

4. Compile the code

javac -cp ~/groovy_and_java/groovy-2.0.4 \
/lib/groovy-2.0.4.jar:. SimpleGroovyCall.java

5. Run the code

java -cp ~/grails/groovy-2.0.4 \
/lib/*:. SimpleGroovyCall

You can find more interesting examples in the book “Scripting in Java: Languages, Frameworks, and Patterns” by Dejan Bosanac

Source: Scripting in Java: Languages, Frameworks, and Patterns
Amazon (in Books): Scripting in Java: Languages, Frameworks, and Patterns
Amazon (Kindle): Scripting in Java: Languages, Frameworks, and Patterns