SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Meta-programming in Groovy
           Lars Blumberg
        Christoph Hartmann
             Arvid Heise


                             29.02.2008
James Strachan wrote

  The Groovy Story




Meta-programming in Groovy    2
“Groovy is an agile dynamic language for the Java
 Platform with many features that are inspired by
languages like Python, Ruby and Smalltalk, making
     them available to Java developers using a
                 Java-like syntax.”
                                         The Groovy web site




         Meta-programming in Groovy                       3
My class is your class



  Groovy

                             Java

 Java Runtime Environment


                                    Adopted from Gina, p. 5

Meta-programming in Groovy                              4
Precompiled vs. direct mode


Code.groovy

      groovyc

 Code.class                Code.groovy

      Java class loader           Groovy class loader

Loaded class               Loaded class



                                    Adopted from Gina, p. 48

  Meta-programming in Groovy                            5
Groovy programming concepts
         Beauty through brevity




  Meta-programming in Groovy      6
Expose the Magic




Meta-programming in Groovy   7
Running Example


class Dog {
   String name = 'dog'

    void bark() {
      System.out.println "$name: woof"
    }

    String toString() {
       name
    }
}




                 Meta-programming in Groovy   8
Metaclasses in Groovy




Meta-programming in Groovy    9
Creating Objects
static void main(args) {        ScriptBytecodeAdapter.invokeNewN(
    new Dog()                       DogExample.class, Dog.class,
}                                   new Object[0])




            Meta-programming in Groovy                       10
Getting Metaclass for Classes
static void main(args) {        ScriptBytecodeAdapter.invokeNewN(
    new Dog()                       DogExample.class, Dog.class,
}                                   new Object[0])




            Meta-programming in Groovy                       11
Example for Custom Metaclass

class WaldiMeta extends MetaClassImpl {
   WaldiMeta() {
     super(GroovySystem.getMetaClassRegistry(), Dog.class)
     initialize()
   }
}

// Instance-based MetaClass
waldi = new Dog(name: 'Waldi')
waldi.metaClass = new WaldiMeta()

// Class-based MetaClass
GroovySystem.getMetaClassRegistry().setMetaClass(Dog.class, new WaldiMeta())
waldi = new Dog(name: 'Waldi')




                 Meta-programming in Groovy                          12
Method Invocation
static void main(args) {
    dog = new Dog()           ScriptBytecodeAdapter. invokeMethodN(
    dog.bark()                    DogExample.class, dog, "bark",
}                                 new Object[0])




            Meta-programming in Groovy                       13
Intercepting Method Calls
static void main(args) {
    dog = new Dog()           ScriptBytecodeAdapter. invokeMethodN(
    dog.bark()                    DogExample.class, dog, "bark",
}                                 new Object[0])




            Meta-programming in Groovy                       14
Interception in GroovyInterceptable



class InterceptingDog extends Dog implements GroovyInterceptable {
   Object invokeMethod(name, args) {
     System.out.println "$this is about to $name"
     metaClass.invokeMethod(this, name, args)
   }
}

dog = new InterceptingDog(name: 'Waldi')
dog.bark()




                                      Waldi is about to bark
                                      Waldi: woof


             Meta-programming in Groovy                        15
Interception using Interceptor
class InterceptingNeighbor implements Interceptor {
   String action
    Object beforeInvoke(object, methodName, arguments) {
        action = methodName
    }
    boolean doInvoke() {
        if(action != 'bark') return true
        println "Neighbor intercepted barking"
        false
    }
}
proxy = ProxyMetaClass.getInstance(Dog.class)
proxy.interceptor = new InterceptingNeighbor()
proxy.use {
   dog = new Dog()                      Neighbor intercepted barking
   dog.bark()
}

                Meta-programming in Groovy                             16
Interception with MetaClass
class BrunoMeta extends MetaClassImpl {
   Object invokeMethod(sender, object, methodName, originalArguments,
                          isCallToSuper, fromInsideClass) {
     println "$object is about to $methodName"
     super.invokeMethod(sender, object, methodName, originalArguments,
                          isCallToSuper, fromInsideClass)
   }

    Object invokeMissingMethod(instance, methodName, arguments) {
      println "$instance does not $methodName"
    }
}

dog = new Dog(name: 'Waldi')               Waldi is about to bark
dog.metaClass = new BrunoMeta()            Waldi: woof
dog.bark()                                 Waldi is about to speak
dog.speak()                                Waldi does not speak


              Meta-programming in Groovy                             17
Evaluating Expressions
      static void main(args) {
          shell = new GroovyShell()
          shell.evaluate("1+1")
      }




Meta-programming in Groovy            18
Become Magician




Meta-programming in Groovy   19
Keep It Simple




                          XML



Class               Hibernate        Table




                       Application

        Meta-programming in Groovy       20
Keep It Simple




Class                    EJB         Table




                       Application

        Meta-programming in Groovy       21
Keep It Simple




              Groovy         Table




               Application

Meta-programming in Groovy       22
Meta-programming in Groovy

• Introspection: fully integrated
   • GroovyObject: getMetaClass, getProperty
   • MetaClass: getProperties, getMethods, getMetaMethods


• Intercession:
   • Interception:
       • GroovyInterceptable: pretend to have function, error handling
       • Interceptor: scope-level; useful for AOP, e.g. logging
       • MetaClass: change or observe behavior on class-level
   • Expando: dynamic behavior and properties on instance-level
   • ExpandoMetaClass: most powerful, dynamic on class-level




          Meta-programming in Groovy                               23
We love you …




Meta-programming in Groovy   24
References

• [Gina]: Dierk Koenig: Groovy in Action
• Codehaus Documentation
  http://groovy.codehaus.org/Documentation
• Practically Groovy
  http://www.ibm.com/developerworks/views/java/li
  braryview.jsp?search_by=practically+groovy
• Groovy Source Code and Mailing List




          Meta-programming in Groovy            25

Contenu connexe

Tendances

TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present FutureDonal Fellows
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseAndrew Eisenberg
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode CompilerDonal Fellows
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Jim Driscoll
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformationshendersk
 
The Ring programming language version 1.7 book - Part 43 of 196
The Ring programming language version 1.7 book - Part 43 of 196The Ring programming language version 1.7 book - Part 43 of 196
The Ring programming language version 1.7 book - Part 43 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184Mahmoud Samir Fayed
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Johnny Sung
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet KotlinJieyi Wu
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 

Tendances (20)

TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Invoke Dynamic
Invoke DynamicInvoke Dynamic
Invoke Dynamic
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transforms
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
Stetl-engine-nlextract-smartem
Stetl-engine-nlextract-smartemStetl-engine-nlextract-smartem
Stetl-engine-nlextract-smartem
 
The Ring programming language version 1.7 book - Part 43 of 196
The Ring programming language version 1.7 book - Part 43 of 196The Ring programming language version 1.7 book - Part 43 of 196
The Ring programming language version 1.7 book - Part 43 of 196
 
The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
Ast transformation
Ast transformationAst transformation
Ast transformation
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 

En vedette

Third review presentation
Third review presentationThird review presentation
Third review presentationArvind Krishnaa
 
Digiaika - Mikä Muuttuu Markkinoinnissa
Digiaika - Mikä Muuttuu MarkkinoinnissaDigiaika - Mikä Muuttuu Markkinoinnissa
Digiaika - Mikä Muuttuu MarkkinoinnissaDarwin Oy
 
Blowin In The Wind
Blowin In The  WindBlowin In The  Wind
Blowin In The Windgoznevi
 
TodiCastle: villa rentals & historic hotel in Umbria
TodiCastle: villa rentals & historic hotel in UmbriaTodiCastle: villa rentals & historic hotel in Umbria
TodiCastle: villa rentals & historic hotel in UmbriaMario Santoro
 
Canvas Based Presentation tool - First Review
Canvas Based Presentation tool - First ReviewCanvas Based Presentation tool - First Review
Canvas Based Presentation tool - First ReviewArvind Krishnaa
 
Asiakkaan Kohtaaminen
Asiakkaan KohtaaminenAsiakkaan Kohtaaminen
Asiakkaan KohtaaminenDarwin Oy
 
The HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or GoldmineThe HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or GoldmineCambridgeIP Ltd
 
Goodrich Global Corporate Profile
Goodrich Global Corporate ProfileGoodrich Global Corporate Profile
Goodrich Global Corporate ProfileGoodrich Global
 
Economics of Green Growth & National Innovation Strategies
Economics of Green Growth & National Innovation StrategiesEconomics of Green Growth & National Innovation Strategies
Economics of Green Growth & National Innovation StrategiesCambridgeIP Ltd
 
P I Infosoft Is Different
P I Infosoft Is DifferentP I Infosoft Is Different
P I Infosoft Is DifferentRajarshi
 
Use of 3D Immersive Technology for the Support of Gifted Learners
Use of 3D Immersive Technology for the Support of Gifted LearnersUse of 3D Immersive Technology for the Support of Gifted Learners
Use of 3D Immersive Technology for the Support of Gifted LearnersGiftedkids.ie
 
CambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Webinar: Developing a fact Based IP StrategyCambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Webinar: Developing a fact Based IP StrategyCambridgeIP Ltd
 
Smart camera monitoring system
Smart camera monitoring systemSmart camera monitoring system
Smart camera monitoring systemArvind Krishnaa
 
Miten läsnäolo toteutetaan ja ylläpidetään?
Miten läsnäolo toteutetaan ja ylläpidetään?Miten läsnäolo toteutetaan ja ylläpidetään?
Miten läsnäolo toteutetaan ja ylläpidetään?Darwin Oy
 
优丽奇中国 公司手册
优丽奇中国 公司手册优丽奇中国 公司手册
优丽奇中国 公司手册Goodrich Global
 
Descrição passo a passo do aparelho de Herbst com cantilever
Descrição passo a passo do aparelho de Herbst com cantileverDescrição passo a passo do aparelho de Herbst com cantilever
Descrição passo a passo do aparelho de Herbst com cantileverConsultório Particular
 

En vedette (20)

Vchitel
VchitelVchitel
Vchitel
 
Third review presentation
Third review presentationThird review presentation
Third review presentation
 
Digiaika - Mikä Muuttuu Markkinoinnissa
Digiaika - Mikä Muuttuu MarkkinoinnissaDigiaika - Mikä Muuttuu Markkinoinnissa
Digiaika - Mikä Muuttuu Markkinoinnissa
 
Blowin In The Wind
Blowin In The  WindBlowin In The  Wind
Blowin In The Wind
 
TodiCastle: villa rentals & historic hotel in Umbria
TodiCastle: villa rentals & historic hotel in UmbriaTodiCastle: villa rentals & historic hotel in Umbria
TodiCastle: villa rentals & historic hotel in Umbria
 
Canvas Based Presentation tool - First Review
Canvas Based Presentation tool - First ReviewCanvas Based Presentation tool - First Review
Canvas Based Presentation tool - First Review
 
Permenpan2014 013
Permenpan2014 013Permenpan2014 013
Permenpan2014 013
 
20131202 1
20131202 120131202 1
20131202 1
 
Asiakkaan Kohtaaminen
Asiakkaan KohtaaminenAsiakkaan Kohtaaminen
Asiakkaan Kohtaaminen
 
The HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or GoldmineThe HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or Goldmine
 
Goodrich Global Corporate Profile
Goodrich Global Corporate ProfileGoodrich Global Corporate Profile
Goodrich Global Corporate Profile
 
Economics of Green Growth & National Innovation Strategies
Economics of Green Growth & National Innovation StrategiesEconomics of Green Growth & National Innovation Strategies
Economics of Green Growth & National Innovation Strategies
 
P I Infosoft Is Different
P I Infosoft Is DifferentP I Infosoft Is Different
P I Infosoft Is Different
 
Use of 3D Immersive Technology for the Support of Gifted Learners
Use of 3D Immersive Technology for the Support of Gifted LearnersUse of 3D Immersive Technology for the Support of Gifted Learners
Use of 3D Immersive Technology for the Support of Gifted Learners
 
CambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Webinar: Developing a fact Based IP StrategyCambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Webinar: Developing a fact Based IP Strategy
 
Smart camera monitoring system
Smart camera monitoring systemSmart camera monitoring system
Smart camera monitoring system
 
Miten läsnäolo toteutetaan ja ylläpidetään?
Miten läsnäolo toteutetaan ja ylläpidetään?Miten läsnäolo toteutetaan ja ylläpidetään?
Miten läsnäolo toteutetaan ja ylläpidetään?
 
优丽奇中国 公司手册
优丽奇中国 公司手册优丽奇中国 公司手册
优丽奇中国 公司手册
 
Descrição passo a passo do aparelho de Herbst com cantilever
Descrição passo a passo do aparelho de Herbst com cantileverDescrição passo a passo do aparelho de Herbst com cantilever
Descrição passo a passo do aparelho de Herbst com cantilever
 
Unit 0
Unit 0Unit 0
Unit 0
 

Similaire à cdac@parag.gajbhiye@groovy metaprogrammning

Embedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationEmbedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationPaolo Predonzani
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaJohn Leach
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouAndres Almiray
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG PadovaJohn Leach
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applicationsrohitnayak
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemKostas Saidis
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for JavaCharles Anderson
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG TrentoJohn Leach
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyAndres Almiray
 
Startup groovysession1
Startup groovysession1Startup groovysession1
Startup groovysession1kyon mm
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersKostas Saidis
 

Similaire à cdac@parag.gajbhiye@groovy metaprogrammning (20)

Embedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationEmbedding Groovy in a Java Application
Embedding Groovy in a Java Application
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and You
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG Padova
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
groovy & grails - lecture 7
groovy & grails - lecture 7groovy & grails - lecture 7
groovy & grails - lecture 7
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG Trento
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
Startup groovysession1
Startup groovysession1Startup groovysession1
Startup groovysession1
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java Developers
 

Plus de Parag Gajbhiye

Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence Parag Gajbhiye
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!Parag Gajbhiye
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!Parag Gajbhiye
 
cdac@amitkumar@test123
cdac@amitkumar@test123cdac@amitkumar@test123
cdac@amitkumar@test123Parag Gajbhiye
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123Parag Gajbhiye
 

Plus de Parag Gajbhiye (9)

Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
 
clodfoundrydoc.pdf
clodfoundrydoc.pdfclodfoundrydoc.pdf
clodfoundrydoc.pdf
 
clodfoundrydoc.pdf
clodfoundrydoc.pdfclodfoundrydoc.pdf
clodfoundrydoc.pdf
 
test123
test123test123
test123
 
test123
test123test123
test123
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
cdac@amitkumar@test123
cdac@amitkumar@test123cdac@amitkumar@test123
cdac@amitkumar@test123
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123
 

cdac@parag.gajbhiye@groovy metaprogrammning

  • 1. Meta-programming in Groovy Lars Blumberg Christoph Hartmann Arvid Heise 29.02.2008
  • 2. James Strachan wrote The Groovy Story Meta-programming in Groovy 2
  • 3. “Groovy is an agile dynamic language for the Java Platform with many features that are inspired by languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.” The Groovy web site Meta-programming in Groovy 3
  • 4. My class is your class Groovy Java Java Runtime Environment Adopted from Gina, p. 5 Meta-programming in Groovy 4
  • 5. Precompiled vs. direct mode Code.groovy groovyc Code.class Code.groovy Java class loader Groovy class loader Loaded class Loaded class Adopted from Gina, p. 48 Meta-programming in Groovy 5
  • 6. Groovy programming concepts Beauty through brevity Meta-programming in Groovy 6
  • 8. Running Example class Dog { String name = 'dog' void bark() { System.out.println "$name: woof" } String toString() { name } } Meta-programming in Groovy 8
  • 10. Creating Objects static void main(args) { ScriptBytecodeAdapter.invokeNewN( new Dog() DogExample.class, Dog.class, } new Object[0]) Meta-programming in Groovy 10
  • 11. Getting Metaclass for Classes static void main(args) { ScriptBytecodeAdapter.invokeNewN( new Dog() DogExample.class, Dog.class, } new Object[0]) Meta-programming in Groovy 11
  • 12. Example for Custom Metaclass class WaldiMeta extends MetaClassImpl { WaldiMeta() { super(GroovySystem.getMetaClassRegistry(), Dog.class) initialize() } } // Instance-based MetaClass waldi = new Dog(name: 'Waldi') waldi.metaClass = new WaldiMeta() // Class-based MetaClass GroovySystem.getMetaClassRegistry().setMetaClass(Dog.class, new WaldiMeta()) waldi = new Dog(name: 'Waldi') Meta-programming in Groovy 12
  • 13. Method Invocation static void main(args) { dog = new Dog() ScriptBytecodeAdapter. invokeMethodN( dog.bark() DogExample.class, dog, "bark", } new Object[0]) Meta-programming in Groovy 13
  • 14. Intercepting Method Calls static void main(args) { dog = new Dog() ScriptBytecodeAdapter. invokeMethodN( dog.bark() DogExample.class, dog, "bark", } new Object[0]) Meta-programming in Groovy 14
  • 15. Interception in GroovyInterceptable class InterceptingDog extends Dog implements GroovyInterceptable { Object invokeMethod(name, args) { System.out.println "$this is about to $name" metaClass.invokeMethod(this, name, args) } } dog = new InterceptingDog(name: 'Waldi') dog.bark() Waldi is about to bark Waldi: woof Meta-programming in Groovy 15
  • 16. Interception using Interceptor class InterceptingNeighbor implements Interceptor { String action Object beforeInvoke(object, methodName, arguments) { action = methodName } boolean doInvoke() { if(action != 'bark') return true println "Neighbor intercepted barking" false } } proxy = ProxyMetaClass.getInstance(Dog.class) proxy.interceptor = new InterceptingNeighbor() proxy.use { dog = new Dog() Neighbor intercepted barking dog.bark() } Meta-programming in Groovy 16
  • 17. Interception with MetaClass class BrunoMeta extends MetaClassImpl { Object invokeMethod(sender, object, methodName, originalArguments, isCallToSuper, fromInsideClass) { println "$object is about to $methodName" super.invokeMethod(sender, object, methodName, originalArguments, isCallToSuper, fromInsideClass) } Object invokeMissingMethod(instance, methodName, arguments) { println "$instance does not $methodName" } } dog = new Dog(name: 'Waldi') Waldi is about to bark dog.metaClass = new BrunoMeta() Waldi: woof dog.bark() Waldi is about to speak dog.speak() Waldi does not speak Meta-programming in Groovy 17
  • 18. Evaluating Expressions static void main(args) { shell = new GroovyShell() shell.evaluate("1+1") } Meta-programming in Groovy 18
  • 20. Keep It Simple XML Class Hibernate Table Application Meta-programming in Groovy 20
  • 21. Keep It Simple Class EJB Table Application Meta-programming in Groovy 21
  • 22. Keep It Simple Groovy Table Application Meta-programming in Groovy 22
  • 23. Meta-programming in Groovy • Introspection: fully integrated • GroovyObject: getMetaClass, getProperty • MetaClass: getProperties, getMethods, getMetaMethods • Intercession: • Interception: • GroovyInterceptable: pretend to have function, error handling • Interceptor: scope-level; useful for AOP, e.g. logging • MetaClass: change or observe behavior on class-level • Expando: dynamic behavior and properties on instance-level • ExpandoMetaClass: most powerful, dynamic on class-level Meta-programming in Groovy 23
  • 24. We love you … Meta-programming in Groovy 24
  • 25. References • [Gina]: Dierk Koenig: Groovy in Action • Codehaus Documentation http://groovy.codehaus.org/Documentation • Practically Groovy http://www.ibm.com/developerworks/views/java/li braryview.jsp?search_by=practically+groovy • Groovy Source Code and Mailing List Meta-programming in Groovy 25