Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Add example of how to declare a base class for a shell script.

...

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));

Evaluate Scripts with a Common Base Class

It is often useful to make your groovy scripts extend a base class of your choosing so that the script can access common methods. This can be achieved by setting the script base class property on the compile configuration and passing this new compiler configuration to the shell.

Code Block
java
java

class ScriptBaseTest {

  @Test
  void extend_groovy_script() {
    def compiler = new CompilerConfiguration()
    compiler.setScriptBaseClass("ScriptBaseTestScript")

    def shell = new GroovyShell(this.class.classLoader, new Binding(), compiler)

    assertEquals shell.evaluate("foo()"), "this is foo"
  }
}

abstract class ScriptBaseTestScript extends Script {
  def foo() {
    "this is foo"
  }
}

Dynamically loading and running Groovy code inside Java

...