@Documented
@Retention(value=SOURCE)
@Target(value={LOCAL_VARIABLE,PACKAGE,TYPE})
public @interface BaseScript
The type of the variable annotated with @BaseScript
must extend Script
.
It will be used as the base script class.
The annotated variable will become shortcut to this
object.
Using this annotation will override base script set by Groovy compiler or
CompilerConfiguration
of GroovyShell
Example usage:
abstract class CustomScript extends Script { int getTheMeaningOfLife() { 42 } } @BaseScript CustomScript baseScript assert baseScript == this assert theMeaningOfLife == 42 assert theMeaningOfLife == baseScript.theMeaningOfLifeIn this example, the base script of the current script will be changed to
CustomScript
allowing usage of getTheMeaningOfLife()
method. baseScript
variable will become typed shortcut for
this
object which enables better IDE support.
The custom base script may implement the run() method and specify a different method name to be used for the script body by declaring a single abstract method. For example:
abstract class CustomScriptBodyMethod extends Script {
abstract def runScript()
def preRun() { println "preRunning" }
def postRun() { println "postRunning" }
def run() {
preRun()
try {
3.times { runScript() }
} finally {
postRun()
}
}
}
@BaseScript
CustomScriptBodyMethod baseScript
println "Script body run"
That will produce the following output:
preRunning Script body run Script body run Script body run postRunningNote that while you can declare arguments for the script body's method, as the AST is currently implemented they are not accessible in the script body code.
More examples:
// Simple Car class to save state and distance. class Car { String state Long distance = 0 } // Custom Script with methods that change the Car's state. // The Car object is passed via the binding. abstract class CarScript extends Script { def start() { this.binding.car.state = 'started' } def stop() { this.binding.car.state = 'stopped' } def drive(distance) { this.binding.car.distance += distance } } // Define Car object here, so we can use it in assertions later on. def car = new Car() // Add to script binding (CarScript references this.binding.car). def binding = new Binding(car: car) // Configure the GroovyShell. def shell = new GroovyShell(this.class.classLoader, binding) // Simple DSL to start, drive and stop the car. // The methods are defined in the CarScript class. def carDsl = ''' start() drive 20 stop() ''' // Run DSL script. shell.evaluate """ // Use BaseScript annotation to set script // for evaluating the DSL. @groovy.transform.BaseScript CarScript carScript $carDsl """ // Checks to see that Car object has changed. assert car.distance == 20 assert car.state == 'stopped'
Modifier and Type | Optional Element and Description |
---|---|
java.lang.Class |
value |