Today vice versa: Call the groovy script we created last time from a Java class:
[JAVA]
package test;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
import java.io.IOException;
import org.codehaus.groovy.control.CompilationFailedException;
public class GroovyScriptRunner {
private String filename=““;
public GroovyScriptRunner(String filename){
this.filename=filename;
}
public boolean run(){
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass;
try {
groovyClass = loader.parseClass(new File(this.filename));
} catch (CompilationFailedException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// let’s call some method on an instance
GroovyObject groovyObject;
try {
groovyObject = (GroovyObject) groovyClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
}
Object[] args = {};
// call main
groovyObject.invokeMethod(„main“, args);
return true;
}
public static void main(String[] args) {
GroovyScriptRunner runner = new GroovyScriptRunner(„test/GroovyTest.groovy“);
runner.run();
}
}
[/JAVA]
More infos can be found here: http://groovy.codehaus.org/Embedding+Groovy