Groovy has been designed to be very lightweight and easy to embed into any Java application system.
You can use BSF 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
Dynamically loading and running Groovy code inside Java
You can use the GroovyClassLoader 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.
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!".
As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library constituted of four jars (asm-1.5.2.jar, asm-util-1.5.2.jar, asm-attrs-1.5.2.jar and asm-analysis-1.5.2). 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.