Package groovy.util

Class DelegatingScript

All Implemented Interfaces:
GroovyObject

public abstract class DelegatingScript
extends Script
Script that performs method invocations and property access like Closure does.

DelegatingScript is a convenient basis for loading a custom-defined DSL as a Script, then execute it. The following sample code illustrates how to do it:

 class MyDSL {
     public void foo(int x, int y, Closure z) { ... }
     public void setBar(String a) { ... }
 }

 CompilerConfiguration cc = new CompilerConfiguration();
 cc.setScriptBaseClass(DelegatingScript.class.getName());
 GroovyShell sh = new GroovyShell(cl,new Binding(),cc);
 DelegatingScript script = (DelegatingScript)sh.parse(new File("my.dsl"))
 script.setDelegate(new MyDSL());
 script.run();
 

my.dsl can look like this:

 foo(1,2) {
     ....
 }
 bar = ...;
 

DelegatingScript does this by delegating property access and method invocation to the delegate object.

More formally speaking, given the following script:

 a = 1;
 b(2);
 

Using DelegatingScript as the base class, the code will run as:

 delegate.a = 1;
 delegate.b(2);
 
... whereas in plain Script, this will be run as:
 binding.setProperty("a",1);
 ((Closure)binding.getProperty("b")).call(2);
 
  • Constructor Details

    • DelegatingScript

      protected DelegatingScript()
    • DelegatingScript

      protected DelegatingScript​(Binding binding)
  • Method Details

    • setDelegate

      public void setDelegate​(Object delegate)
      Sets the delegation target.
    • invokeMethod

      public Object invokeMethod​(String name, Object args)
      Description copied from class: Script
      Invoke a method (or closure in the binding) defined.
      Specified by:
      invokeMethod in interface GroovyObject
      Overrides:
      invokeMethod in class Script
      Parameters:
      name - method to call
      args - arguments to pass to the method
      Returns:
      value
    • getProperty

      public Object getProperty​(String property)
      Description copied from interface: GroovyObject
      Retrieves a property value.
      Specified by:
      getProperty in interface GroovyObject
      Overrides:
      getProperty in class Script
      Parameters:
      property - the name of the property of interest
      Returns:
      the given property
    • setProperty

      public void setProperty​(String property, Object newValue)
      Description copied from interface: GroovyObject
      Sets the given property to the new value.
      Specified by:
      setProperty in interface GroovyObject
      Overrides:
      setProperty in class Script
      Parameters:
      property - the name of the property of interest
      newValue - the new value for the property
    • getDelegate

      public Object getDelegate()