Monday, March 31st, 2008

The GroovyScriptEngine

The Groovy lessons reflect my first steps into Groovy territory. Groovy is a programming language that builds on Java and is quite seamlessly integrated with Java.

After learning to run simple stuff in the GroovyShell you naturally want to proceed to something resembling an application. Run it conveniently using the GroovyScriptEngine. Enter the following lines in a GroovyShell:


  1. span style="color: #ff0000;">"app-directory""App.groovy"

In the simplest case you have a number of .groovy files in a directory. The path of this directory ("app-directory") is the argument to the GroovyScriptEngine constructor. In the run method you must tell the engine the name of the file containing the main method of the application. Remember, in Groovy the main method is typically introduced like this,

static main(args) {...

Note that we are only dealing with source files. The engine transparently takes care of compilation.

Quite probably your application contains more than the App.groovy file. In order not to complicate things, put one class per file and use Java naming conventions. For instance, put the Gadgets class in a file named Gadgets.groovy. In this way the script engine will have no problem finding additional classes.

There is a gotcha hovering over this area. If you are used to Java you have been spoiled letting javac take care of mutual dependencies between classes. The Groovy script engine is different. It does not resolve mutual dependencies, but just refuses to run the application, complaining about the main class. Same thing if it fails to compile one of the additional classes.

In a simple application, avoid mutual dependencies. If the script engine refuses to run, use the Groovy compiler (groovyc) to compile the additional classes. That will help you discover and correct the problems.

In summary, the Groovy script engine does a great job of simplifying the code and test cycle.

Comments are closed.