SlideShare a Scribd company logo
Feelin’ Groovy: An Afternoon of Reflexive Metaprogramming Matt Stine UM-CIS Seminar September 3, 2008
Who Am I? Matt Stine Ole Miss CIS Class of 2001 Group Leader Research Application Development St. Jude Children’s Research Hospital Memphis/Mid-South Java User Group Founder Husband to Wendy (Ole Miss Mathematics 2001) Father to Four (Abby, Isabella, Ali Kate, and Grant)
Agenda Brief introduction to Groovy What is reflexive metaprogramming? How does Groovy support reflexive metaprogramming? What are some applications of reflexive metaprogramming? A look at Internal DSL’s (Domain Specific Languages)
Groovy: A Brief Tour Agile, dynamic language for the JVM Flexible, Java-like syntax Additional power features inspired by languages like Python, Ruby and Smalltalk Project founded by James Strachan and Bob McWhirter in 2003 Became JSR-241 in 2004 Now led by Guillaume Laforge and the company he co-founded, G2One, Inc. ( http://www.g2one.com ) Currently at version 1.5.6 (also 1.6-beta-1) http://groovy.codehaus.org
Groovy: A Brief Tour Absolutely everything is an object – no primitives! Lots of syntactical sugar for lists, maps, ranges, regular expressions, etc.
Groovy: A Brief Tour Dynamic (duck) typing
Groovy: A Brief Tour Dynamic (duck) typing It’s all in what you “respond to!”
Groovy: A Brief Tour Closures an anonymous chunk of code that may take arguments, return a value, and reference and use variables declared in its surrounding scope “ resembles” anonymous inner classes in Java In functional language parlance, such an anonymous code block might be referred to as an anonymous lambda expression Why Closures?
Groovy: A Brief Tour The traditional way:
Groovy: A Brief Tour A “groovier” way:
Groovy: A Brief Tour Metaprogramming Let’s go deeper….
Reflexive Metaprogramming? Metaprogramming:  writing programs that write or manipulate programs as data (code generation) Reflexive metaprogramming:   writing programs that manipulate themselves as data Source: H. C. Cunningham. Reflexive metaprogramming in Ruby, Journal of Computing Sciences in Colleges, Vol, 22, No. 5, pp. 145-146, CCSC, May 2007.
How Groovy supports RM Meta Object Protocol (MOP) Groovy (like Ruby and Smalltalk) possesses a higher level concept called a MetaClass The MetaClass decides the behavior of the actual class  at runtime . Anything  is possible at runtime.
How Groovy supports RM With Groovy’s MOP you can add, remove, replace: Static and instance methods Constructors Fields Properties On any Groovy or Java class…. at runtime!
Groovy Object
Groovy interceptors
POJOs, POGOs, and their MetaClass
How Groovy Handles POGO Method Calls
How Groovy supports RM Categories (from Objective-C) Open Classes (via  ExpandoMetaClass ) Add methods to interfaces Intercept method calls by overriding  invokeMethod() Provide “missing method” behavior by overriding  methodMissing() “ Borrow” methods from other classes Dynamically construct method property names at runtime
How Groovy supports RM Other constructs: Operator overloading Method pointers Closures Expandos (objects on-the-fly) Dynamic evaluation of Strings as Groovy code
Three areas of focus: Method interception (Groovy AOP) Method injection Method synthesis
Groovy AOP An easy way to implement Aspect-Oriented Programming (AOP) like method interception or method advice AOP? Separate “crosscutting concerns” into separate modules These modules “advise” methods during program execution Three types of advice: Before After Around
Two approaches: Let the object do it Implement the  GroovyInterceptable  interface Not desirable if: You’re not the author of the class The class is a Java class You want to introduce interception dynamically Let the object’s  MetaClass  do it
Using GroovyInterceptable
Using MetaClass
Using MetaClass (on a POJO)
Method Injection Adding behavior dynamically into classes Two methods: Categories ExpandoMetaClass
Categories Controlled way to inject methods Effect contained within a block of code Alters your class’s MetaClass Within the scope of the block and executing thread Change reversed on block exit Can be nested Can apply multiple categories in a single block
Category Method Injection
Category Method Injection (2)
ExpandoMetaClass Groovy’s implementation of “open classes” Can add to POGO’s and POJO’s: Methods Properties Constructors Static methods Can borrow methods from other classes Can do injection not only at the class level, but at the instance level (POGO’s only)
ExpandoMetaClass  Injection Add a method:
ExpandoMetaClass  Injection Add a property:
ExpandoMetaClass  Injection Add a static method:
ExpandoMetaClass  Injection Add a constructor:
Method Synthesis Create new methods with flexible and dynamic names “on-the-fly” Names not decided ahead of time Class users can decide names as long as they follow established conventions Groovy provides  methodMissing()  to implement method synthesis
Method Synthesis
Method Synthesis There’s a catch… Repeated calls to a nonexistent method involve repeated performance hits to evaluate Make efficient by injecting the method on first invocation: “ Intercept, Cache, Invoke” pattern Coined by Graeme Roche, Grails project lead
Intercept, Cache, Invoke
Method Synthesis Can also be done using  ExpandoMetaClass When? If you can’t modify the class If the class is a Java class How? Implement  methodMissing()  on the class’s  ExpandoMetaClass Can also synthesize methods into specific instances of POGOs
A Look at Internal DSL’s From Martin Fowler: The basic idea of a domain specific language (DSL) is a computer language that's targeted to a particular kind of problem, rather than a general purpose language that's aimed at any kind of software problem. This Internal DSL (also referred to as an embedded DSL) uses the constructs of the programming language itself to define to DSL.
Why DSL’s? Use a  more expressive  language than a general programming language Share a  common metaphor  between developers and domain experts Have  domain experts help  design the business logic of an application Avoid cluttering business  code with too much boilerplate technical code Cleanly  seperate business logic  from application code
Groovy + DSL’s Groovy’s metaprogramming constructs support the easy implementation of DSL’s!!! Let’s take a look…
An Example DSL A mini-DSL for manipulating measures and units by leveraging the JScience library From: Laforge, Guillaume. A Domain-Specific Languages for unit manipulations.  http://groovy. dzone .com/news/domain-specific-language-unit- , March 2008.
What is JScience? Java library leveraging generics to represent various measurable quantities. JSR-275: javax.measure.* reference implementation Can be used for measuring mass, length, time, amperes, volts, …
How to represent a mass with JScience?
Wouldn’t it be nicer… If we could write this the way a physicist would write it? What if we could write  3 kg + 2 kg ? We’ll get close: def sum = 3.kg + 2.kg
DSL Implementation
DSL Implementation
DSL Implementation
DSL Implementation
QUESTIONS?!?!?!
Resources http://groovy. codehaus .org http://groovy. dzone .com http://grails.org
References Rocher, Graeme. Rapid Web Development with Groovy and Grails: Module 1. Java University @ JavaOne 2007. Rocher, Graeme. Dynamic Groovy: Groovy’s Equivalent to Ruby Open Classes.  http: //graemerocher . blogspot .com/2007/06/dynamic-groovy-groovys-equivalent-to.html , June 2007. Davis, Scott.  Groovy Recipes: Greasing the Wheels of Java . Pragmatic Bookshelf, January 2008. Davis, Scott. Groovy: The Red Pill. NFJS Gateway Software Symposium, March 2008. Cunningham, H. C. Reflexive metaprogramming in Ruby, Journal of Computing Sciences in Colleges, Vol, 22, No. 5, pp. 145-146, CCSC, May 2007. Almiray, Andres. MetaProgramming with Groovy I.  http://groovy. dzone . com/articles/metaprogramming-groovy-I , January 2008. Almiray, Andres. MetaProgramming with Groovy II.  http://groovy. dzone . com/articles/metaprogramming-groovy-ii-expa , February 2008. Laforge, Guillaume and John Wilson. Tutorial: Domain Specific Languages in Groovy. QCon 2007.  http: //glaforge .free.fr/groovy/QCon-Tutorial-Groovy-DSL-2-colour. pdf   Laforge, Guillaume. A Domain-Specific Language for unit manipulations.  http://groovy. dzone .com/news/domain-specific-language-unit- , March 2008. Subramaniam, Venkat.  Programming Groovy: Dynamic Productivity for the Java Developer . Pragmatic Bookshelf, March 2008. Multiple Example Code Extracts and Figures  from  Programming Groovy .  http://pragprog.com/titles/vslg . (Used with permission.) Groovy User Guide.  http://groovy.codehaus.org/User+Guide

More Related Content

PDF
Java/J2EE interview Qestions
PPTX
Online Lecture Design
PDF
Class notes(week 9) on multithreading
PDF
37 Java Interview Questions
PPTX
Metaprogramming with Groovy
DOCX
Viva file
PDF
Concurrency on the JVM
PDF
Java Concurrency Starter Kit
Java/J2EE interview Qestions
Online Lecture Design
Class notes(week 9) on multithreading
37 Java Interview Questions
Metaprogramming with Groovy
Viva file
Concurrency on the JVM
Java Concurrency Starter Kit

What's hot (8)

PPTX
Groovy
PPT
Groovy And Grails
ODP
DOC
C# interview questions
DOCX
C# interview quesions
PPTX
Meta Programming in Groovy
PDF
Greach 2014 - Metaprogramming with groovy
PPT
python training | python course | python online training
Groovy
Groovy And Grails
C# interview questions
C# interview quesions
Meta Programming in Groovy
Greach 2014 - Metaprogramming with groovy
python training | python course | python online training
Ad

Viewers also liked (20)

KEY
Getting Things Done
PPT
Java(tm) Technology On Google App Engine
PDF
The Cloud Native Journey
PDF
Functional solid
PDF
Lattice: A Cloud-Native Platform for Your Spring Applications
PPTX
Competing with Software: It Takes a Platform -- Devops @ EMC World
PDF
Linux Collaboration Summit Keynote: Transformation: It Takes a Platform
PDF
It's the End of the Cloud as We Know It
PDF
Deploying Microservices to Cloud Foundry
PPTX
Evolving Devops: The Benefits of PaaS and Application Dial Tone
PDF
Velocity NY 2016 - Devops: Who Does What?
PPTX
Pivotal Cloud Platform Roadshow Keynote
PDF
Reactive Fault Tolerant Programming with Hystrix and RxJava
PDF
Devops Enterprise Summit: My Great Awakening: 
Top “Ah-ha” Moments As Former ...
PPTX
12 Factor, or Cloud Native Apps – What EXACTLY Does that Mean for Spring Deve...
PPTX
Cloud Foundry Introduction (w Demo) at Silicon Valley Code Camp
PPTX
Removing Barriers Between Dev and Ops
PDF
Software Quality in the Devops World: The Impact of Continuous Delivery on Te...
PDF
Vert.x
PPTX
Cloud Foundry Platform Operations - CF Summit 2015
Getting Things Done
Java(tm) Technology On Google App Engine
The Cloud Native Journey
Functional solid
Lattice: A Cloud-Native Platform for Your Spring Applications
Competing with Software: It Takes a Platform -- Devops @ EMC World
Linux Collaboration Summit Keynote: Transformation: It Takes a Platform
It's the End of the Cloud as We Know It
Deploying Microservices to Cloud Foundry
Evolving Devops: The Benefits of PaaS and Application Dial Tone
Velocity NY 2016 - Devops: Who Does What?
Pivotal Cloud Platform Roadshow Keynote
Reactive Fault Tolerant Programming with Hystrix and RxJava
Devops Enterprise Summit: My Great Awakening: 
Top “Ah-ha” Moments As Former ...
12 Factor, or Cloud Native Apps – What EXACTLY Does that Mean for Spring Deve...
Cloud Foundry Introduction (w Demo) at Silicon Valley Code Camp
Removing Barriers Between Dev and Ops
Software Quality in the Devops World: The Impact of Continuous Delivery on Te...
Vert.x
Cloud Foundry Platform Operations - CF Summit 2015
Ad

Similar to Feelin' Groovy: An Afternoon of Reflexive Metaprogramming (20)

PPT
Dynamic Languages on the JVM
PDF
JavaScript Miller Columns
PPT
Future Programming Language
PDF
Groovy Metaprogramming for Dummies
PDF
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
PDF
Why don't you Groovy?
PDF
Groovy Finesse
PDF
Groovy Finesse
PPTX
Suga java training_with_footer
PDF
Java Interview Questions
PDF
Understanding And Using Reflection
PPTX
Lecture 1.1 - Introducing Java.pptx3eeeee
PPT
Classes and Objects
PPT
Intro Java Rev010
PPTX
java_inheritance_oop_20250730110153.pptx
PPT
Csci360 20 (1)
PPT
Csci360 20
PDF
20 most important java programming interview questions
PPT
Java_notes.ppt
PDF
Method overloading and method overriding
Dynamic Languages on the JVM
JavaScript Miller Columns
Future Programming Language
Groovy Metaprogramming for Dummies
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
Why don't you Groovy?
Groovy Finesse
Groovy Finesse
Suga java training_with_footer
Java Interview Questions
Understanding And Using Reflection
Lecture 1.1 - Introducing Java.pptx3eeeee
Classes and Objects
Intro Java Rev010
java_inheritance_oop_20250730110153.pptx
Csci360 20 (1)
Csci360 20
20 most important java programming interview questions
Java_notes.ppt
Method overloading and method overriding

More from Matt Stine (19)

PDF
Architectures That Bend but Don't Break
PDF
Cloud Native Architecture Patterns Tutorial
PDF
Resilient Architecture
PDF
Cloud Foundry: The Best Place to Run Microservices
PDF
To Microservices and Beyond
PDF
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
PDF
Building Distributed Systems with Netflix OSS and Spring Cloud
PDF
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
PDF
A Recovering Java Developer Learns to Go
PDF
Agile Development with OSGi
PDF
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
PDF
The Seven Wastes of Software Development
PPTX
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
PDF
Achieve Your Goals
PPT
Deploying Grails to Morph App Space
KEY
JUG Leadership Lessons Learned
KEY
Introduction to JMS and Message-Driven POJOs
KEY
Case Study: SRM 2.0 - A next generation shared resource management system bui...
KEY
Polyglot OSGi
Architectures That Bend but Don't Break
Cloud Native Architecture Patterns Tutorial
Resilient Architecture
Cloud Foundry: The Best Place to Run Microservices
To Microservices and Beyond
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
Building Distributed Systems with Netflix OSS and Spring Cloud
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
A Recovering Java Developer Learns to Go
Agile Development with OSGi
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
The Seven Wastes of Software Development
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Achieve Your Goals
Deploying Grails to Morph App Space
JUG Leadership Lessons Learned
Introduction to JMS and Message-Driven POJOs
Case Study: SRM 2.0 - A next generation shared resource management system bui...
Polyglot OSGi

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Modernizing your data center with Dell and AMD
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Electronic commerce courselecture one. Pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Spectral efficient network and resource selection model in 5G networks
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Big Data Technologies - Introduction.pptx
cuic standard and advanced reporting.pdf
Network Security Unit 5.pdf for BCA BBA.
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Modernizing your data center with Dell and AMD
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Review of recent advances in non-invasive hemoglobin estimation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Electronic commerce courselecture one. Pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectral efficient network and resource selection model in 5G networks

Feelin' Groovy: An Afternoon of Reflexive Metaprogramming

  • 1. Feelin’ Groovy: An Afternoon of Reflexive Metaprogramming Matt Stine UM-CIS Seminar September 3, 2008
  • 2. Who Am I? Matt Stine Ole Miss CIS Class of 2001 Group Leader Research Application Development St. Jude Children’s Research Hospital Memphis/Mid-South Java User Group Founder Husband to Wendy (Ole Miss Mathematics 2001) Father to Four (Abby, Isabella, Ali Kate, and Grant)
  • 3. Agenda Brief introduction to Groovy What is reflexive metaprogramming? How does Groovy support reflexive metaprogramming? What are some applications of reflexive metaprogramming? A look at Internal DSL’s (Domain Specific Languages)
  • 4. Groovy: A Brief Tour Agile, dynamic language for the JVM Flexible, Java-like syntax Additional power features inspired by languages like Python, Ruby and Smalltalk Project founded by James Strachan and Bob McWhirter in 2003 Became JSR-241 in 2004 Now led by Guillaume Laforge and the company he co-founded, G2One, Inc. ( http://www.g2one.com ) Currently at version 1.5.6 (also 1.6-beta-1) http://groovy.codehaus.org
  • 5. Groovy: A Brief Tour Absolutely everything is an object – no primitives! Lots of syntactical sugar for lists, maps, ranges, regular expressions, etc.
  • 6. Groovy: A Brief Tour Dynamic (duck) typing
  • 7. Groovy: A Brief Tour Dynamic (duck) typing It’s all in what you “respond to!”
  • 8. Groovy: A Brief Tour Closures an anonymous chunk of code that may take arguments, return a value, and reference and use variables declared in its surrounding scope “ resembles” anonymous inner classes in Java In functional language parlance, such an anonymous code block might be referred to as an anonymous lambda expression Why Closures?
  • 9. Groovy: A Brief Tour The traditional way:
  • 10. Groovy: A Brief Tour A “groovier” way:
  • 11. Groovy: A Brief Tour Metaprogramming Let’s go deeper….
  • 12. Reflexive Metaprogramming? Metaprogramming: writing programs that write or manipulate programs as data (code generation) Reflexive metaprogramming: writing programs that manipulate themselves as data Source: H. C. Cunningham. Reflexive metaprogramming in Ruby, Journal of Computing Sciences in Colleges, Vol, 22, No. 5, pp. 145-146, CCSC, May 2007.
  • 13. How Groovy supports RM Meta Object Protocol (MOP) Groovy (like Ruby and Smalltalk) possesses a higher level concept called a MetaClass The MetaClass decides the behavior of the actual class at runtime . Anything is possible at runtime.
  • 14. How Groovy supports RM With Groovy’s MOP you can add, remove, replace: Static and instance methods Constructors Fields Properties On any Groovy or Java class…. at runtime!
  • 17. POJOs, POGOs, and their MetaClass
  • 18. How Groovy Handles POGO Method Calls
  • 19. How Groovy supports RM Categories (from Objective-C) Open Classes (via ExpandoMetaClass ) Add methods to interfaces Intercept method calls by overriding invokeMethod() Provide “missing method” behavior by overriding methodMissing() “ Borrow” methods from other classes Dynamically construct method property names at runtime
  • 20. How Groovy supports RM Other constructs: Operator overloading Method pointers Closures Expandos (objects on-the-fly) Dynamic evaluation of Strings as Groovy code
  • 21. Three areas of focus: Method interception (Groovy AOP) Method injection Method synthesis
  • 22. Groovy AOP An easy way to implement Aspect-Oriented Programming (AOP) like method interception or method advice AOP? Separate “crosscutting concerns” into separate modules These modules “advise” methods during program execution Three types of advice: Before After Around
  • 23. Two approaches: Let the object do it Implement the GroovyInterceptable interface Not desirable if: You’re not the author of the class The class is a Java class You want to introduce interception dynamically Let the object’s MetaClass do it
  • 27. Method Injection Adding behavior dynamically into classes Two methods: Categories ExpandoMetaClass
  • 28. Categories Controlled way to inject methods Effect contained within a block of code Alters your class’s MetaClass Within the scope of the block and executing thread Change reversed on block exit Can be nested Can apply multiple categories in a single block
  • 31. ExpandoMetaClass Groovy’s implementation of “open classes” Can add to POGO’s and POJO’s: Methods Properties Constructors Static methods Can borrow methods from other classes Can do injection not only at the class level, but at the instance level (POGO’s only)
  • 32. ExpandoMetaClass Injection Add a method:
  • 33. ExpandoMetaClass Injection Add a property:
  • 34. ExpandoMetaClass Injection Add a static method:
  • 35. ExpandoMetaClass Injection Add a constructor:
  • 36. Method Synthesis Create new methods with flexible and dynamic names “on-the-fly” Names not decided ahead of time Class users can decide names as long as they follow established conventions Groovy provides methodMissing() to implement method synthesis
  • 38. Method Synthesis There’s a catch… Repeated calls to a nonexistent method involve repeated performance hits to evaluate Make efficient by injecting the method on first invocation: “ Intercept, Cache, Invoke” pattern Coined by Graeme Roche, Grails project lead
  • 40. Method Synthesis Can also be done using ExpandoMetaClass When? If you can’t modify the class If the class is a Java class How? Implement methodMissing() on the class’s ExpandoMetaClass Can also synthesize methods into specific instances of POGOs
  • 41. A Look at Internal DSL’s From Martin Fowler: The basic idea of a domain specific language (DSL) is a computer language that's targeted to a particular kind of problem, rather than a general purpose language that's aimed at any kind of software problem. This Internal DSL (also referred to as an embedded DSL) uses the constructs of the programming language itself to define to DSL.
  • 42. Why DSL’s? Use a more expressive language than a general programming language Share a common metaphor between developers and domain experts Have domain experts help design the business logic of an application Avoid cluttering business code with too much boilerplate technical code Cleanly seperate business logic from application code
  • 43. Groovy + DSL’s Groovy’s metaprogramming constructs support the easy implementation of DSL’s!!! Let’s take a look…
  • 44. An Example DSL A mini-DSL for manipulating measures and units by leveraging the JScience library From: Laforge, Guillaume. A Domain-Specific Languages for unit manipulations. http://groovy. dzone .com/news/domain-specific-language-unit- , March 2008.
  • 45. What is JScience? Java library leveraging generics to represent various measurable quantities. JSR-275: javax.measure.* reference implementation Can be used for measuring mass, length, time, amperes, volts, …
  • 46. How to represent a mass with JScience?
  • 47. Wouldn’t it be nicer… If we could write this the way a physicist would write it? What if we could write 3 kg + 2 kg ? We’ll get close: def sum = 3.kg + 2.kg
  • 53. Resources http://groovy. codehaus .org http://groovy. dzone .com http://grails.org
  • 54. References Rocher, Graeme. Rapid Web Development with Groovy and Grails: Module 1. Java University @ JavaOne 2007. Rocher, Graeme. Dynamic Groovy: Groovy’s Equivalent to Ruby Open Classes. http: //graemerocher . blogspot .com/2007/06/dynamic-groovy-groovys-equivalent-to.html , June 2007. Davis, Scott. Groovy Recipes: Greasing the Wheels of Java . Pragmatic Bookshelf, January 2008. Davis, Scott. Groovy: The Red Pill. NFJS Gateway Software Symposium, March 2008. Cunningham, H. C. Reflexive metaprogramming in Ruby, Journal of Computing Sciences in Colleges, Vol, 22, No. 5, pp. 145-146, CCSC, May 2007. Almiray, Andres. MetaProgramming with Groovy I. http://groovy. dzone . com/articles/metaprogramming-groovy-I , January 2008. Almiray, Andres. MetaProgramming with Groovy II. http://groovy. dzone . com/articles/metaprogramming-groovy-ii-expa , February 2008. Laforge, Guillaume and John Wilson. Tutorial: Domain Specific Languages in Groovy. QCon 2007. http: //glaforge .free.fr/groovy/QCon-Tutorial-Groovy-DSL-2-colour. pdf Laforge, Guillaume. A Domain-Specific Language for unit manipulations. http://groovy. dzone .com/news/domain-specific-language-unit- , March 2008. Subramaniam, Venkat. Programming Groovy: Dynamic Productivity for the Java Developer . Pragmatic Bookshelf, March 2008. Multiple Example Code Extracts and Figures from Programming Groovy . http://pragprog.com/titles/vslg . (Used with permission.) Groovy User Guide. http://groovy.codehaus.org/User+Guide

Editor's Notes

  • #3: Of course, no introduction of myself would be complete without introducing my wife (CLICK!) And my four children (CLICK!)
  • #7: Consider the following Groovy class….it’s a Duck, and as any good Duck should, it walks like a duck and quacks like a duck. (CLICK!) Now, consider this Groovy class….it’s a MentalPatient, and it just so happens to walk like a duck and quack like a duck. (CLICK!) Now, consider the Groovy class….it claims to walk with ducks. It defines one method, with an interesting type declaration in its signature (CLICK!) Here we have a dynamic type declaration….”def”….this allows us to pass in either a Duck or a MentalPatient…and to WalksWithDucks, as long as it walks like a duck…. (CLICK!) It’s a duck!!!
  • #8: At the end of the day, it’s all in what you respond to! (CLICK!) Here we see one of Groovy’s metaprogramming constructs, the “respondsTo” method, which allows us to see whether or not a given object responds to certain method calls, irrespective of any class or interface implementation
  • #16: In Groovy application, 3 kinds of objects: POJO’s (Plain Old Java Objects) -> regular Java objects created in Java or other JVM languages (JRuby, Jython, etc.) POGO’s (Plain Old Groovy Objects) -> written in Groovy, extend java.lang.Object, implement groovy.lang.GroovyObject Groovy interceptors -> written in Groovy and implement GroovyInterceptable invokeMethod(), getProperty(), setProperty() – make Groovy objects highly dynamic – can be used to work w/ methods and properties created on the fly getMetaClass()/setMetaClass() – make it very easy to create proxies to intercept and also inject methods on a POGO
  • #17: Marker interface that extends GroovyObject All method calls – both existing and nonexisting methods – on an object implementing this interface are intercepted by its invokeMethod()
  • #18: Groovy allows metaprogramming for POJO’s and POGO’s POJOS – Groovy maintains a MetaClassRegistry class of MetaClasses POGOS – direct reference to their MetaClass When you call a method: Groovy first checks whether the target is a POJO or POGO, and handles such calls differently If it is a POJO, Groovy fetches its MetaClass from the MetaClassRegistry and delegates method invocation to it. Any interceptors or methods you’ve defined on its MetaClass take precedence over the original method of the POJO For POGO’s, Groovy takes a few extra steps (CLICK!)
  • #19: If the class implements GroovyInterceptable, all calls get routed to its invokeMethod() If not, then Groovy looks for the method first in the POGO’s MetaClass, and then if not found, in the POGO itself, executing in that order of preference If the POGO does not have either, it then looks for a property with that method name. If found, and if its type is Closure, it invokes the Closure. If no closure property, it invokes methodMissing() if it exists If not, it invokes the POGO’s invokeMethod() If all else fails, Groovy throws a MissingMethodException indicating the failure of the call
  • #25: Suppose we have a Car class for which we want to call its check() method to perform filtering prior to any other method call CLICK! Here we implement invokeMethod()….CLICK! First, we check to see if the name of the method is not check()….if not, we get access to the check() MetaMethod and invoke it….CLICK! Next, we try to access the MetaMethod for the method that was called…CLICK! If we don’t get a null, we know we have a valid method, and we invoke it…CLICK! Otherwise, we delegate the call to the Car MetaClass’s invokeMethod()….the default implementation throwing a MissingMethodException….CLICK! Here’s some client code…we call the 3 valid methods and then one invalid method…CLICK! And here’s the output….notice that for start() and drive() we run the filter….but when check() is called directly, we do not….and again, notice the MissingMethodException on speed()
  • #26: We can do the same thing using MetaClass…there are a few subtle differences: (CLICK!) We actually implement invokeMethod on the Car MetaClass by implementing a closure and assigning it to that method name. (CLICK!) Instead of passing “this” to invoke, we pass “delegate.” In a closure, delegate refers to the object that owns the closure. (CLICK!) Lastly, we call invokeMissingMethod() on the metaClass since we are already executing invokeMethod() and would not want to call that method recursively. invokeMissingMethod() actually delegates to invokeMethod() in the case of existing methods, and to missingMethod() in the case of nonexisting methods
  • #27: We can also use MetaClass on a POJO…in this case the java.lang.Integer class (CLICK!) Again, we’re implementing a closure and assigning it to invokeMethod on the Integer class (CLICK!) The closure simply checks for a valid method call, invokes pre-filtering code, invokes the method, and invokes post-filtering code. Here is some client code….the first two calls exist on Integer, while the third does not… (CLICK!) And here is the output…..notice the execution of the filters for the valid method calls and then the MissingMethodException thrown on the call to empty()
  • #30: So here we’re going to implement a StringUtil class containing a single method, toSSN(), that we’d like to be vailable on both String and StringBuffer…it will format the contents of the string as a social security number. So to do category injection, there are a few requirements: (CLICK!) First, you need a static method…(CLICK!) That accepts at least one parameter (the object for which the method is to be injected) (CLICK!) You write a use block, with the Category class as the argument…in this case, any Object inside the use block will have access to the toSSN() method because we left toSSN() dynamically typed (CLICK!) Objects outside the scope of the use block will not have toSSN()….(CLICK!) And here is the output…
  • #31: I want to show you a second example of this to futher illustrate the flexibility….here we have a FindUtil class with an extractOnly() method….(CLICK!) Again, the method is static….(CLICK!) It takes the object (in this case a String) on which to inject the method as the first parameter….(CLICK!) And it also takes a second argument, in this case a closure that we expect to return a boolean value…(CLICK!) Inside the method, we iterate over each character in the String and append to the result only characters for which the closure returns true. You’ll see “it” here, which happens to be the default argument in closures if none are specified…(CLICK!) We setup our use block and execute the code (CLICK!) In this case, we pass in a closre that returns true only if the scanned character is a ‘4’ or a ‘5’….given the String of characters we start with, we get 54 as the output…
  • #33: Here we’d like to add a method….daysFromNow()….to the Integer class…it will return an instance of java.util.Date equal to the Integer number of days from today….(CLICK!) Now you can tell I only made this slide a couple of days ago …. :-)
  • #34: We can also add a property in a similar way by implementing the “getter” method for a property called daysFromNow….this allows us to drop the parenthesis, creating a more “fluent” or human readable interface, something you like to shoot for when building domain specific languages…CLICK! Here’s the output….
  • #35: We can also add a static method by implementing methods on the static property of the metaClass…here’s we’ll add a method indicating whether or not its argument is an even number….CLICK! Again, here’s the output….
  • #36: The last method type we can add in is a constructor…we do this by appending a closure to the existing set of constructors on Integer….in this case, we want to construct an Integer equal to the current day of the year…CLICK! And the output….
  • #38: Let’s define a Person class that plays several sports…CLICK! First we’ll implement methodMissing()…CLICK! We’ll search for the suffix of the method named called….in this case we’re expecting method calls like “playFootball” or “playPolo”….CLICK! Having found it, we’ll return a String that says we’re “playing” the sport….here we’re using Groovy’s ability to execute arbitrary Groovy code embedded in a String inside the ${} construct…. CLICK! If we don’t find a legal method name, we throw a MissingMethodException….here’ some client code with several legal calls and one illegal call….CLICK! And here’s the output….notice that methodMissing() is not called for the work() method, but is for all of the sports-related methods….and we got a MissingMethodException for politics, which is usually not a sport, depending on who you’re talking to….
  • #40: Now let’s implement the Intercept, Cache, Invoke pattern on our Person class…CLICK! First we intercept the method call, just as we did before. Having found it….CLICK! We implement a closure and add it to the Person’s MetaClass…again we’re using Groovy’s String evaluation capabilities to dynamically construct the method name….CLICK! We then return the result of the closure we just implemented….CLICK! Quickly notice the static initializer block….here I’m simply “touching” the metaClass for Person. The reason for this is an eccentricity in Groovy in that ExpandoMetaClass is not the default MetaClass for Groovy, however once you access it the first time it is replaced with an instance of EMC. This may be changed in future versions….CLICK! Here’s some client code…CLICK!….and here’s the output. Notice that methodMissing() is only called once
  • #49: So here’s the beginning of our DSL….the first thing we do is enable the ExpandoMetaClass globally….this causes methods we add to a parent class, in this case Number, to be available to its children….CLICK! Next we reimplement Number’s get Property method….we assign it a closure that uses Jscience’s API to instantiate an Amount equal to the value of the Number instance and units specified by the propery name…. I’ve added a few examples of this and….CLICK!….here’s the output
  • #50: The next step is to define our operator overloading….since Jscience doesn’t use the same operation names as Groovy, we need to implement a few closures to massage out the differences…..I’ve put here examples of Multiplication Division Addition Subtraction Powers Opposites And comparisons…and CLICK! Here’s the output…..notice on the power example we mixed metric and english units, and Jscience guessed that we’d want the output in metric units (indicated by the question mark)…
  • #51: Our third step is to allow us to specify inverse units in a clean way, just like a physicist would. In a Groovy script like this one, all variables are local variables….however you can also pass in variables through a Binding, allowing for easy integration with existing Java code, etc. Here we’re going to implement a binding that will ignore references to the out property, which represents System.out….otherwise, it will return an amount equal to 1 unit of the symbol representing the property we tried to access…. Now, you can see these examples of inverse units, such as kilometers per hour, milligrams per Liter, etc…CLICK! And here’s the output of this portion….
  • #52: Finally, we’d like to easily do conversions between different units, so we define a to() method on Amount’s metaclass….here’s some examples of that and CLICK! The output