SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPTX
TclOO: Past Present Future
Donal Fellows
 
PPT
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
PDF
Better DSL Support for Groovy-Eclipse
Andrew Eisenberg
 
PDF
Infinum android talks_10_getting groovy on android
Infinum
 
PDF
The TclQuadcode Compiler
Donal Fellows
 
PPT
JDK1.7 features
india_mani
 
KEY
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 
PDF
Invoke Dynamic
Dmitry Buzdin
 
PDF
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
PPTX
Kotlin – the future of android
DJ Rausch
 
PDF
Introduction to Groovy runtime metaprogramming and AST transforms
Marcin Grzejszczak
 
ODP
Groovy AST Transformations
hendersk
 
PDF
Stetl-engine-nlextract-smartem
Just van den Broecke
 
PDF
The Ring programming language version 1.7 book - Part 43 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.3 book - Part 39 of 184
Mahmoud Samir Fayed
 
PDF
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
ODP
Ast transformation
Gagan Agrawal
 
PDF
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Johnny Sung
 
PPTX
Nice to meet Kotlin
Jieyi Wu
 
PDF
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
 
TclOO: Past Present Future
Donal Fellows
 
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Better DSL Support for Groovy-Eclipse
Andrew Eisenberg
 
Infinum android talks_10_getting groovy on android
Infinum
 
The TclQuadcode Compiler
Donal Fellows
 
JDK1.7 features
india_mani
 
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 
Invoke Dynamic
Dmitry Buzdin
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Kotlin – the future of android
DJ Rausch
 
Introduction to Groovy runtime metaprogramming and AST transforms
Marcin Grzejszczak
 
Groovy AST Transformations
hendersk
 
Stetl-engine-nlextract-smartem
Just van den Broecke
 
The Ring programming language version 1.7 book - Part 43 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 39 of 184
Mahmoud Samir Fayed
 
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
Ast transformation
Gagan Agrawal
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Johnny Sung
 
Nice to meet Kotlin
Jieyi Wu
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
 

Viewers also liked (20)

PPT
Vchitel
Tanya Puzir
 
PDF
Third review presentation
Arvind Krishnaa
 
PPT
Digiaika - Mikä Muuttuu Markkinoinnissa
Darwin Oy
 
PPS
Blowin In The Wind
goznevi
 
PPT
TodiCastle: villa rentals & historic hotel in Umbria
Mario Santoro
 
PDF
Canvas Based Presentation tool - First Review
Arvind Krishnaa
 
PDF
Permenpan2014 013
Mohammad Subhan
 
PDF
20131202 1
Mohammad Subhan
 
PPT
Asiakkaan Kohtaaminen
Darwin Oy
 
PDF
The HFA pMDI Patent Landscape: Minefield or Goldmine
CambridgeIP Ltd
 
PDF
Goodrich Global Corporate Profile
Goodrich Global
 
PDF
Economics of Green Growth & National Innovation Strategies
CambridgeIP Ltd
 
PPSX
P I Infosoft Is Different
Rajarshi
 
PDF
Use of 3D Immersive Technology for the Support of Gifted Learners
Giftedkids.ie
 
PDF
CambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Ltd
 
PPT
Smart camera monitoring system
Arvind Krishnaa
 
PDF
Miten läsnäolo toteutetaan ja ylläpidetään?
Darwin Oy
 
PDF
优丽奇中国 公司手册
Goodrich Global
 
PDF
Descrição passo a passo do aparelho de Herbst com cantilever
Consultório Particular
 
PPSX
Unit 0
Rocio Torres
 
Vchitel
Tanya Puzir
 
Third review presentation
Arvind Krishnaa
 
Digiaika - Mikä Muuttuu Markkinoinnissa
Darwin Oy
 
Blowin In The Wind
goznevi
 
TodiCastle: villa rentals & historic hotel in Umbria
Mario Santoro
 
Canvas Based Presentation tool - First Review
Arvind Krishnaa
 
Permenpan2014 013
Mohammad Subhan
 
20131202 1
Mohammad Subhan
 
Asiakkaan Kohtaaminen
Darwin Oy
 
The HFA pMDI Patent Landscape: Minefield or Goldmine
CambridgeIP Ltd
 
Goodrich Global Corporate Profile
Goodrich Global
 
Economics of Green Growth & National Innovation Strategies
CambridgeIP Ltd
 
P I Infosoft Is Different
Rajarshi
 
Use of 3D Immersive Technology for the Support of Gifted Learners
Giftedkids.ie
 
CambridgeIP Webinar: Developing a fact Based IP Strategy
CambridgeIP Ltd
 
Smart camera monitoring system
Arvind Krishnaa
 
Miten läsnäolo toteutetaan ja ylläpidetään?
Darwin Oy
 
优丽奇中国 公司手册
Goodrich Global
 
Descrição passo a passo do aparelho de Herbst com cantilever
Consultório Particular
 
Unit 0
Rocio Torres
 
Ad

Similar to [email protected]@groovy metaprogrammning (20)

PPT
Groovy Basics
Wes Williams
 
PPT
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
PPTX
Meta Programming in Groovy
NexThoughts Technologies
 
PDF
Greach 2014 - Metaprogramming with groovy
Iván López Martín
 
PPTX
MetaProgramming with Groovy
NexThoughts Technologies
 
PPTX
Metaprogramming with Groovy
Ali Tanwir
 
PPT
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Guillaume Laforge
 
PPTX
Groovy And Grails Introduction
Eric Weimer
 
PDF
Oscon Java Testing on the Fast Lane
Andres Almiray
 
PDF
Whats New In Groovy 1.6?
Guillaume Laforge
 
PDF
Groovy Metaprogramming for Dummies
Darren Cruse
 
PPTX
getting-your-groovy-on
Christopher Johannsen
 
PDF
Groovy 2 and beyond
Guillaume Laforge
 
PDF
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
PDF
Groovy 2.0 webinar
Guillaume Laforge
 
KEY
Groovy & Grails
Marcel Overdijk
 
PDF
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
PDF
Groovy On Trading Desk (2010)
Jonathan Felch
 
PDF
Groovy a Scripting Language for Java
Charles Anderson
 
PDF
Apache Groovy's Metaprogramming Options and You
Andres Almiray
 
Groovy Basics
Wes Williams
 
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
Meta Programming in Groovy
NexThoughts Technologies
 
Greach 2014 - Metaprogramming with groovy
Iván López Martín
 
MetaProgramming with Groovy
NexThoughts Technologies
 
Metaprogramming with Groovy
Ali Tanwir
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Guillaume Laforge
 
Groovy And Grails Introduction
Eric Weimer
 
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Whats New In Groovy 1.6?
Guillaume Laforge
 
Groovy Metaprogramming for Dummies
Darren Cruse
 
getting-your-groovy-on
Christopher Johannsen
 
Groovy 2 and beyond
Guillaume Laforge
 
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
Groovy 2.0 webinar
Guillaume Laforge
 
Groovy & Grails
Marcel Overdijk
 
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
Groovy On Trading Desk (2010)
Jonathan Felch
 
Groovy a Scripting Language for Java
Charles Anderson
 
Apache Groovy's Metaprogramming Options and You
Andres Almiray
 
Ad

More from Parag Gajbhiye (9)

ODP
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Parag Gajbhiye
 
PDF
clodfoundrydoc.pdf
Parag Gajbhiye
 
PDF
clodfoundrydoc.pdf
Parag Gajbhiye
 
PDF
test123
Parag Gajbhiye
 
PDF
test123
Parag Gajbhiye
 
PDF
My cool new Slideshow!
Parag Gajbhiye
 
PDF
My cool new Slideshow!
Parag Gajbhiye
 
PDF
cdac@amitkumar@test123
Parag Gajbhiye
 
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
Parag Gajbhiye
 
clodfoundrydoc.pdf
Parag Gajbhiye
 
clodfoundrydoc.pdf
Parag Gajbhiye
 
My cool new Slideshow!
Parag Gajbhiye
 
My cool new Slideshow!
Parag Gajbhiye
 
cdac@amitkumar@test123
Parag Gajbhiye
 

[email protected]@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