Adding default methods with a Groovy BaseScript
Having talked about nouns in our DSL by adding new variables from the Binding, it’s time to talk a little bit about verbs – there’s a number of ways to do this in Groovy, so let’s start by looking at a BaseScript for Scripts.
A BaseScript is, effectively, the super class for the Script that’s executed dynamically from GroovyShell. To use a BaseScript, create an abstract class that extends Script, implementing the methods you want to enable in your scripts. Here’s a very simple example:
package basescripttest; import groovy.lang.Script; abstract public class BaseScript extends Script { void hello(String name) { System.out.println("hello "+name); } }
This BaseScript will provide a single method to your script: hello – taking a single argument, a String. Note that you could just as easily use a Groovy class for the same purpose:
package basescripttest abstract class BaseScript extends Script{ def hello(name) { println "hello $name" } }
Which does the same thing. To use it in a program, use the CompilerConfiguration class, which allows various modifications of how the GroovyShell parser acts at runtime. Note that you need to pass the fully qualified name of the class as a String to the setScriptBaseClass.
CompilerConfiguration config = new CompilerConfiguration(); config.setScriptBaseClass("basescripttest.BaseScript"); GroovyShell shell = new GroovyShell(config); Script script = shell.parse("hello('Jim')"); script.run();
So, to recap, we’re executing the following script:
hello('Jim')
Which is outputting the following text to stdout:
Jim
In this example, we just use the (now default provided) hello function in the BaseScript from within the provided class. This is a very simple example – we’ll go into more detail next time.
Great article Jim. This is something what I was looking for and very nicely explained.
developer883
June 18, 2013 at 11:47 AM