Search

Dark theme | Light theme

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
    }
}