» Articles » using groovy 'scriptlets' in java

using groovy 'scriptlets' in java

My goal is to ‘outsource’ parts of a java application into groovy scriptlets, and have the main program (written in java) load those scriptlets and execute them in a predefined fashion.

What I want is that those scriptles can be used to extend the main application in a very easy way, so that no compilation is necessary, no classpath needs to be extended, and no bunnies get killed.

Here’s my very simple approach:

ScriptletInterface.java:
public interface ScriptletInterface {
    /**
     * this method is always called. use this to initialize
     * data structures and the like.
     */
    public void init();
}
Scriptlet.groovy:
public class Scriptlet implements ScriptletInterface {
      public void runit() {
      	  println "running :-)"
      }
      public int getResult() {
      	  return 42
      }
}

And here is the calling code:

String fileName = "scriptlet.groovy";
// important: we need to set the context classloader as the parent for the
// groovy scriptlet, otherwise the interface wont be found.
ClassLoader parent = CallingClass.class.getClassLoader();
GroovyClassLoader gcl = new GroovyClassLoader(parent);
Class clazz = gcl.parseClass(new File(fileName));
ScriptletInterface scriptlet = (ScriptletInterface)clazz.newInstance();
scriptlet.runit();

There’s a sample showing the usage with an interface, but that one has a bug that leads to a ‘unable to resolve class’-error. The GroovyClassLoader must have a parent.

‘scriptlet’ can now be used like a java class.

Note to self: add support for BSF later on.