New DelegatingScript Base Class – Groovy 2.2 feature
Script base class of Compiler Configuration can be customized.
Delegating Script Base Class helps to delegate the calls in a script to a class that has DSL methods/functions & variables.
import org.codehaus.groovy.control.CompilerConfiguration def scriptInfo=''' model="Nexus 5" getModel() ''' class MobileDealer{ String model void getModel(){ println "Mobile : $model" } } def compilerConfig=new CompilerConfiguration() compilerConfig.scriptBaseClass=DelegatingScript.class.name def shell=new GroovyShell(compilerConfig) def script=shell.parse(scriptInfo) MobileDealer m=new MobileDealer() script.setDelegate(m) script.run()
- Line 1 – import package of Compiler Configuration class
- Line 3-6 has the script where the delegate is set and is run finally.
- Line 8-13 has the class declaration of the delegate class MobileDealer. The methods and variables in this class can be reused commonly in scripts.
- Line 15–new instance of compiler configuration is created
- Line 16–DelegatingScript is set as the base class for that particular compilerConfiguration instance
- Line 17-new groovyShell instance is created with the present compiler Configuration
- Line 18-The above “scriptInfo” is parsed to DelegatingScript type
- Line 20-MobileDealer class is set as delegate in the script.
- Line 21-the script is run.
REFERENCE:
http://jira.codehaus.org/browse/GROOVY-6076
Leave a comment