@Documented @Retention(value=SOURCE) @Target(value={LOCAL_VARIABLE,PACKAGE,TYPE}) public @interface BaseScript
The type of the variable annotated with 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:
class CustomScript extends Script {
int getTheMeaningOfLife() { 42 }
}
@BaseScript CustomScript baseScript
assert baseScript == this
assert theMeaningOfLife == 42
assert theMeaningOfLife == baseScript.theMeaningOfLife
In 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.
public abstract Class value