Java 6 includes built-in support for JSR 223: Scripting for the Java Platform API classes. This framework can be used to host Script Engines in Java Applications. Numerous Scripting engines are available.
Here is how you can use JSR 223 to talk to Groovy from Java:
The output is:
To make this example work, if you're running Groovy 1.5.x, add
groovy-engine.jar from https://scripting.dev.java.net/ to your CLASSPATH and run this program using Java 6. But since Groovy 1.6, Groovy already contains the groovy scripting engine compliant with JSR-223.
This next example illustrates calling an invokable function:
And when run, results in:
Groovy has many mechanisms for integration with Java, some of which provider richer options than available with JSR 223 (e.g. greater configurability and more security control). JSR 223 is recommended when you need to keep the choice of language used flexible and you don't require integration mechanisms not supported by JSR-223.
See also: JSR-223 access to other JVM languages