Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

You can evaluate any expression or script in Groovy using the GroovyShell.
The GroovyShell allows you to pass in and out variables via the Binding object.

Code Block
java
java
// call groovy expressions from Java code
Binding binding = new Binding();
binding.setVariable("foo", new Integer(2));
GroovyShell shell = new GroovyShell(binding);

Object value = shell.evaluate("println 'Hello World!'; x = 123; return foo * 10");
assert value.equals(new Integer(20));
assert binding.getVariable("x").equals(new Integer(123));

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:

...