MyArchiBook

New DelegatingScript Base Class – Groovy 2.2 feature

leave a comment »

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 15new instance of compiler configuration is created
  • Line 16DelegatingScript 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

Advertisements

Written by thangaveluaishwarya

February 14, 2014 at 12:32 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: