Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 19 Next »

Groovy has been designed to be very lightweight and easy to embed into any Java application system.

You can use


to embed any scripting language into your Java code; however Groovy offers a lighter weight and closer integration. There are three main approaches

Evaluate scripts or expressions using the shell

You can evaluate any expression or script in Groovy using the


The GroovyShell allows you to pass in and out variables via the



Dynamically loading and running Groovy code inside Java

You can use the


to load classes dynamically into a Java program and execute them (or use them) directly.
The following Java code shows an example...

If you have an interface you wish to use which you implement in the Groovy script you can use it as follows

This works fine if the Groovy class implements the inferface MyInterface. myObject can from then on be used as every other Java object implementing MyInterface.

One thing to remember is that the parseClass will try to create an object from your String fileName.  Another way to do the gcl.parseClass is:

Full Example:

Note that all of the error handling has been removed -- you won't be able to do this in a java class.  I actually use the Interface invokation for Groovy inside of a Utility Class.

The GroovyScriptEngine

The most complete solution for people who want to embed groovy scripts into their servers and have them reloaded on modification is the GroovyScriptEngine. You initialize the GroovyScriptEngine with a set of CLASSPATH like roots that can be URLs or directory names. You can then execute any Groovy script within those roots. The GSE will also track dependencies between scripts so that if any dependent script is modified the whole tree will be recompiled and reloaded.

Additionally, each time you run a script you can pass in a Binding that contains properties that the script can access. Any properties set in the script will also be available in that binding after the script has run. Here is a simple example:


This will print "Hello, world!".

Runtime dependencies

As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library constituted of four jars (asm-2.1.jar, asm-util-2.1.jar, asm-attrs-2.1.jar and asm-analysis-2.1). That's it. So just add these 5 jars to your classpath and away you go, you can happily embed Groovy into your application.

Alternatively, instead of several jars, you can use groovy-all-1.0-beta-x.jar included in the GROOVY_HOME/embeddable directory of your distribution: this jar contains both Groovy and ASM combined in a single and convenient archive, with the ASM classes in a different namespace, so conflits with other libraries also using ASM will be avoided (smile)

  • No labels