Recently I looked for an opportunity to run Groovy scripts inside of Java applications. On one side I want to execute Groovy scripts. On the other side I want to bind Groovy classes to Java classes via interfaces. The following examples shows how to do this. I use Maven to implement my tasks.
1 Execution of Groovy scripts
1.1: Add Maven Groovy dependency (pom.xml)
groovy
groovy
1.1-rc-1
1.2: Create hello world Groovy script in src/main/java/ directory
package org.developers.blog.groovy.webservice.example //$name variable will be forwarded from Java code println "Hello $name!" //return value to invoking Java method return "ok"
1.3: Create Java class src/main/java/package directory
package org.developers.blog.groovy.webservice.example;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.File;
public class GroovyEmbeddedExample {
public static void main(String[] args) throws Exception {
Binding binding = new Binding();
//will be forwared to the script environment
binding.setVariable("name", "Rafael Sobek");
GroovyShell shell = new GroovyShell(binding);
//executes the script and get the return value
Object value =
shell.evaluate(new File("src/main/java/script01.groovy"));
System.out.println(value);
}
}
1.4: Result
Hello Rafael Sobek! ok
2.0: Dynamically loading of Groovy classes in Java code
2.1: Creates Java interface
public interface ITurnoverCalculation {
void calc();
}
2.2: Implement Groovy class
public class TurnoverCalculation implements ITurnoverCalculation {
public void calc() {
print("Turnover is: " + Math.abs(Math.random() * 1000000));
}
}
2.3: Instance and call Groovy class via Java interface
//binding + linking of groovy classes
GroovyClassLoader gcl = new GroovyClassLoader();
//parsing and adding Groovy class to the Groovy class loader
String groovyClassPath =
"src/main/java/org/developers/blog/groovy/"
+ "webservice/example/TurnoverCalculation.groovy";
Class clazz = gcl.parseClass(
new File(groovyClassPath));
//creation of instance per reflection API
Object instance = clazz.newInstance();
System.out.println("" + instance.getClass());
//bind directly to Java / cast to interface
ITurnoverCalculation turnoverGroovyCalc = (ITurnoverCalculation) instance;
//call Groovy method from Java code
turnoverGroovyCalc.calc();
You can download all examples here.
Regards
Rafael Sobek
Technorati Tags: groovy embed groovy

I'm curious why you're using such an old version of Groovy!!!!