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

ODP
Groovy and Grails intro
PPTX
Making Java Groovy (JavaOne 2013)
PDF
Groovy Grails DevJam Jam Session
PDF
Grooscript gr8conf
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
PPTX
Metaprogramming Techniques In Groovy And Grails
ODP
AST Transformations at JFokus
PPTX
Adventures in TclOO
Groovy and Grails intro
Making Java Groovy (JavaOne 2013)
Groovy Grails DevJam Jam Session
Grooscript gr8conf
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
Metaprogramming Techniques In Groovy And Grails
AST Transformations at JFokus
Adventures in TclOO

What's hot (20)

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

Viewers also liked (20)

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

Similar to cdac@parag.gajbhiye@groovy metaprogrammning (20)

PDF
Embedding Groovy in a Java Application
PDF
Groovy And Grails JUG Sardegna
PDF
Apache Groovy's Metaprogramming Options and You
PDF
Introduction to Oracle Groovy
PDF
Groovy And Grails JUG Padova
PDF
Atlassian Groovy Plugins
PDF
Groovy 2.0 webinar
PPT
Groovy & Grails: Scripting for Modern Web Applications
PPTX
MetaProgramming with Groovy
PPTX
Metaprogramming with Groovy
PPT
What's New in Groovy 1.6?
PDF
Apache Groovy: the language and the ecosystem
KEY
groovy & grails - lecture 7
ZIP
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
PDF
Groovy a Scripting Language for Java
PDF
Groovy And Grails JUG Trento
PPT
Eclipsecon08 Introduction To Groovy
KEY
Startup groovysession1
PDF
Oscon Java Testing on the Fast Lane
PDF
An Introduction to Gradle for Java Developers
Embedding Groovy in a Java Application
Groovy And Grails JUG Sardegna
Apache Groovy's Metaprogramming Options and You
Introduction to Oracle Groovy
Groovy And Grails JUG Padova
Atlassian Groovy Plugins
Groovy 2.0 webinar
Groovy & Grails: Scripting for Modern Web Applications
MetaProgramming with Groovy
Metaprogramming with Groovy
What's New in Groovy 1.6?
Apache Groovy: the language and the ecosystem
groovy & grails - lecture 7
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy a Scripting Language for Java
Groovy And Grails JUG Trento
Eclipsecon08 Introduction To Groovy
Startup groovysession1
Oscon Java Testing on the Fast Lane
An Introduction to Gradle for Java Developers

More from Parag Gajbhiye (9)

ODP
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
PDF
clodfoundrydoc.pdf
PDF
clodfoundrydoc.pdf
PDF
PDF
PDF
My cool new Slideshow!
PDF
My cool new Slideshow!
PDF
cdac@amitkumar@test123
PDF
cdac@parag.gajbhiye@test123
Introduction to Git(BitBucket) , Continuous Integration (Bamboo) & Confluence
clodfoundrydoc.pdf
clodfoundrydoc.pdf
My cool new Slideshow!
My cool new Slideshow!
cdac@amitkumar@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