SlideShare a Scribd company logo
1 of 28
Download to read offline
Groovy
Metaprogramming
for Dummies
Darren Cruse
(not a professional speaker: please no heckling or throwing of food
per Groovy User Group Regulation 103a subsection e)
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
•Who am I?
Once too good for “scripting”
Former Perl Nut
Recent Javascript Graduate
Improving Groovy Skills
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
•What’s this talk about?
metaprogramming = “programming the
program”
metaprogramming = what makes groovy
really groovy!
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
• Who’s this talk for?
Ideally: Someone who’s seen a bit of groovy and aspires to get
to the next level
Someone still unconvinced groovy’s power and productivity is
sufficiently greater than java’s to merit learning a language
with such a silly name.
(and you advanced guys feel free to dive in and help me out!)
Monday, June 7, 2010
Builders = Metaprogramming Magic
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails'
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
Monday, June 7, 2010
Builders = Metaprogramming Magic
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
Monday, June 7, 2010
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails'
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Builders = Metaprogramming Magic
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
Monday, June 7, 2010
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
XML Builders = An alternative
Syntax for XML
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
Monday, June 7, 2010
But How?
(is it code or is it data?)
Any sufficiently advanced
technology is
indistinguishable from
magic.
Arthur C. Clarke,
English physicist & science fiction author (1917 - )
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails' // & is converted to &amp;
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Monday, June 7, 2010
The Answer Lies in Groovy’s Nature As a
Dynamic Language
(as distinguished from java)
compile
time
Java
run
time
compile
time
Groovy
run
time
Monday, June 7, 2010
Java Compilation
java
source
byte
code
Monday, June 7, 2010
Groovy Compilation
groovy
source
byte
code
meta
program
Monday, June 7, 2010
The Program Generated...
Evaluates Your Program At Runtime...
...it does so using a framework that is
designed for you to plug into...
When you do so you are “programming
the program”...
i.e. metaprogramming.
Monday, June 7, 2010
This framework is called
the “Meta Object Protocol”
(“protocol” in the sense of an “api”)
MOPMonday, June 7, 2010
If you’re familiar with a
framework like Struts...
This really isn’t that different:
Instead of mapping url requests to the code that handles them, you’re
mapping actual method calls and property accesses to the code that
handles them!
Instead of using struts-config.xml to do the mapping, you’re using
actual code in the form of data structures called “meta classes”
The simplest and coolest of these is called the
ExpandoMetaClass!
Monday, June 7, 2010
All Groovy Objects Implement...
public interface GroovyObject {
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
MetaClass getMetaClass();
void setMetaClass(MetaClass metaClass);
}
(This the heartbeat of the MOP)
Monday, June 7, 2010
MetaClasses Implement these methods for a class
and thereby define the behavior of the class.
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
The beauty of ExpandoMetaClass is that you can add
methods and properties to classes simply by assigning
them - it expands indefinitely (like a Map).
Monday, June 7, 2010
So The Magic Is Revealed
(dynamic dispatch and missing methods)
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails' // & is converted to &amp;
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Monday, June 7, 2010
When it comes to Groovy’s syntax...
What you can write is fixed by the
parser (like most languages)...
but there’s lots of optional stuff
optional “()“, optional “;”,
optional “[]” (sometimes)...
so much optional it sounds nuts!
but there’s a method to the
madness.
Monday, June 7, 2010
Combining the MOP with Groovy’s loose syntax...
You can highjack the meaning
behind what the evaluator thinks
are method or property calls
but which supericially look more
“declarative” than imperative
more “what” than “how”
the result can be shorter and
clearer than java
Monday, June 7, 2010
Grails uses this stuff a lot...
It has a lot of these “domain specific languages” or
“DSL”s
but this talk is about groovy it’s not about grails
But grails is the best example of where these approaches
are used all over the place to do amazing things with just a
little code...
so this talk is about grails
DSL
But it’s not
it’s about how grails does things under the covers
about how *groovy* does things under the covers
so this is a meta talk about grails
Exactly (exact-o-mundo)
Monday, June 7, 2010
And DSLs aren’t the only thing
The combination of closures and metaclasses
can allow much coolness including:
AOP
IOC
Memoization
RMI via REST
(well, at least the factory pattern)
(a fancy word for caching)
(how many acronyms you gonna use?)
(without the AOP)
(coolness = productivity)
Monday, June 7, 2010
The preceding will be demonstrated with some
delightful code examples.
But first...
Monday, June 7, 2010
A Review of Closures for Newbies...
A java assignment:
int val = 3;
A java function:
public int func(int a, int b) {
return a + b;
}
Or in Groovy:
def val = 3
A groovy function:
def func(a, b) {
a + b
}
Monday, June 7, 2010
A Review of Closures for Newbies...
def func = (a, b) {
a + b
}
Closures are anonymous functions that can be assigned
as *values*...
From the previously slide you can *almost* guess the syntax:
Close! Above itʼs the variable that holds the name so itʼs on
the left thatʼs correct. The wrong part is the parameters:
def func = { a, b ->
a + b
}
Groovyʼs syntax is nice because the “{“ and “}” clearly mark the “code block”.
Monday, June 7, 2010
A Review of Closures for Newbies...
def class Counter {
int count
def increment = { count ++ }
}
One more thing about closures - regarding scoping...
A closure defined in the lexical scope of other code can refer
to itʼs variables. This surrounding code is the “owner”:
But when closures are assigned to other objects, thereʼs more to
life than just the surrounding code - esp. note the delegate:
this: as in Java, this refers to the instance of the enclosing
class where a Closure is defined
owner : the enclosing object (this or a surrounding Closure)
delegate : by default the same as owner, but changeable for
example in a builder or ExpandoMetaClass
Monday, June 7, 2010
A Review of Closures for Newbies...
def postiveOnly(Closure c) {
list.each { val ->
if(val > 0)
c.call(val)
}
}
Oh! And one more thing about closures...
Groovy has syntactic sugar which allows a function taking a
closure as itʼs final argument can be called with the closure
passed after the functions closing paren:
Can be called like so:
postiveOnly { val -> println “$val is > 0” }
And lastly: the default parameter if none is specified is simply “it”:
postiveOnly { println “$it is > 0” }
Monday, June 7, 2010
Finally: some real metaprogramming...
String.metaClass.shout = { delegate.toUpperCase(); }
println "Groovy".shout()
Add a method to a class:
And yes, you could even:
(but just because you can doesnʼt mean you will)
This just shows what a flexible and powerful language groovy is.
postiveOnly { println “$it is > 0” }
String.metaClass.toUpperCase = { delegate.toLowerCase(); }
println "Groovy".toUpperCase()
A programming language for grownups.
(with a silly name)
Monday, June 7, 2010

More Related Content

What's hot

Simple Jackson with DropWizard
Simple Jackson with DropWizardSimple Jackson with DropWizard
Simple Jackson with DropWizardTatu Saloranta
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Jackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVJackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVTatu Saloranta
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
[A 3]Javascript oop for xpages developers - public
[A 3]Javascript oop for xpages developers - public[A 3]Javascript oop for xpages developers - public
[A 3]Javascript oop for xpages developers - publicKazunori Tatsuki
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011sullis
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlinleonsabr
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 

What's hot (19)

Simple Jackson with DropWizard
Simple Jackson with DropWizardSimple Jackson with DropWizard
Simple Jackson with DropWizard
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Jackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVJackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSV
 
Classes and Inheritance
Classes and InheritanceClasses and Inheritance
Classes and Inheritance
 
Dom
DomDom
Dom
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
[A 3]Javascript oop for xpages developers - public
[A 3]Javascript oop for xpages developers - public[A 3]Javascript oop for xpages developers - public
[A 3]Javascript oop for xpages developers - public
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011Comparing JSON Libraries - July 19 2011
Comparing JSON Libraries - July 19 2011
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlin
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
tutorial54
tutorial54tutorial54
tutorial54
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 

Similar to Groovy Metaprogramming Magic

Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Feelin' Groovy: An Afternoon of Reflexive MetaprogrammingFeelin' Groovy: An Afternoon of Reflexive Metaprogramming
Feelin' Groovy: An Afternoon of Reflexive MetaprogrammingMatt Stine
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
 
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
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersKostas Saidis
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...Burt Beckwith
 
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
 
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
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196Mahmoud Samir Fayed
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Guillaume Laforge
 

Similar to Groovy Metaprogramming Magic (20)

Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Feelin' Groovy: An Afternoon of Reflexive MetaprogrammingFeelin' Groovy: An Afternoon of Reflexive Metaprogramming
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
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
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 
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
 
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
 
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?
 
OOP Day 1
OOP Day 1OOP Day 1
OOP Day 1
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
Grooscript greach
Grooscript greachGrooscript greach
Grooscript greach
 
Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 

Recently uploaded

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Recently uploaded (20)

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

Groovy Metaprogramming Magic

  • 1. Groovy Metaprogramming for Dummies Darren Cruse (not a professional speaker: please no heckling or throwing of food per Groovy User Group Regulation 103a subsection e) Monday, June 7, 2010
  • 2. Meta Stuff (about the meta talk) •Who am I? Once too good for “scripting” Former Perl Nut Recent Javascript Graduate Improving Groovy Skills Monday, June 7, 2010
  • 3. Meta Stuff (about the meta talk) •What’s this talk about? metaprogramming = “programming the program” metaprogramming = what makes groovy really groovy! Monday, June 7, 2010
  • 4. Meta Stuff (about the meta talk) • Who’s this talk for? Ideally: Someone who’s seen a bit of groovy and aspires to get to the next level Someone still unconvinced groovy’s power and productivity is sufficiently greater than java’s to merit learning a language with such a silly name. (and you advanced guys feel free to dive in and help me out!) Monday, June 7, 2010
  • 5. Builders = Metaprogramming Magic def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } Monday, June 7, 2010
  • 6. Builders = Metaprogramming Magic <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> Monday, June 7, 2010
  • 7. def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Builders = Metaprogramming Magic <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> Monday, June 7, 2010
  • 8. book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } XML Builders = An alternative Syntax for XML <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> Monday, June 7, 2010
  • 9. But How? (is it code or is it data?) Any sufficiently advanced technology is indistinguishable from magic. Arthur C. Clarke, English physicist & science fiction author (1917 - ) def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' // & is converted to &amp; comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Monday, June 7, 2010
  • 10. The Answer Lies in Groovy’s Nature As a Dynamic Language (as distinguished from java) compile time Java run time compile time Groovy run time Monday, June 7, 2010
  • 13. The Program Generated... Evaluates Your Program At Runtime... ...it does so using a framework that is designed for you to plug into... When you do so you are “programming the program”... i.e. metaprogramming. Monday, June 7, 2010
  • 14. This framework is called the “Meta Object Protocol” (“protocol” in the sense of an “api”) MOPMonday, June 7, 2010
  • 15. If you’re familiar with a framework like Struts... This really isn’t that different: Instead of mapping url requests to the code that handles them, you’re mapping actual method calls and property accesses to the code that handles them! Instead of using struts-config.xml to do the mapping, you’re using actual code in the form of data structures called “meta classes” The simplest and coolest of these is called the ExpandoMetaClass! Monday, June 7, 2010
  • 16. All Groovy Objects Implement... public interface GroovyObject { Object invokeMethod(String name, Object args); Object getProperty(String propertyName); void setProperty(String propertyName, Object newValue); MetaClass getMetaClass(); void setMetaClass(MetaClass metaClass); } (This the heartbeat of the MOP) Monday, June 7, 2010
  • 17. MetaClasses Implement these methods for a class and thereby define the behavior of the class. Object invokeMethod(String name, Object args); Object getProperty(String propertyName); void setProperty(String propertyName, Object newValue); The beauty of ExpandoMetaClass is that you can add methods and properties to classes simply by assigning them - it expands indefinitely (like a Map). Monday, June 7, 2010
  • 18. So The Magic Is Revealed (dynamic dispatch and missing methods) <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' // & is converted to &amp; comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Monday, June 7, 2010
  • 19. When it comes to Groovy’s syntax... What you can write is fixed by the parser (like most languages)... but there’s lots of optional stuff optional “()“, optional “;”, optional “[]” (sometimes)... so much optional it sounds nuts! but there’s a method to the madness. Monday, June 7, 2010
  • 20. Combining the MOP with Groovy’s loose syntax... You can highjack the meaning behind what the evaluator thinks are method or property calls but which supericially look more “declarative” than imperative more “what” than “how” the result can be shorter and clearer than java Monday, June 7, 2010
  • 21. Grails uses this stuff a lot... It has a lot of these “domain specific languages” or “DSL”s but this talk is about groovy it’s not about grails But grails is the best example of where these approaches are used all over the place to do amazing things with just a little code... so this talk is about grails DSL But it’s not it’s about how grails does things under the covers about how *groovy* does things under the covers so this is a meta talk about grails Exactly (exact-o-mundo) Monday, June 7, 2010
  • 22. And DSLs aren’t the only thing The combination of closures and metaclasses can allow much coolness including: AOP IOC Memoization RMI via REST (well, at least the factory pattern) (a fancy word for caching) (how many acronyms you gonna use?) (without the AOP) (coolness = productivity) Monday, June 7, 2010
  • 23. The preceding will be demonstrated with some delightful code examples. But first... Monday, June 7, 2010
  • 24. A Review of Closures for Newbies... A java assignment: int val = 3; A java function: public int func(int a, int b) { return a + b; } Or in Groovy: def val = 3 A groovy function: def func(a, b) { a + b } Monday, June 7, 2010
  • 25. A Review of Closures for Newbies... def func = (a, b) { a + b } Closures are anonymous functions that can be assigned as *values*... From the previously slide you can *almost* guess the syntax: Close! Above itʼs the variable that holds the name so itʼs on the left thatʼs correct. The wrong part is the parameters: def func = { a, b -> a + b } Groovyʼs syntax is nice because the “{“ and “}” clearly mark the “code block”. Monday, June 7, 2010
  • 26. A Review of Closures for Newbies... def class Counter { int count def increment = { count ++ } } One more thing about closures - regarding scoping... A closure defined in the lexical scope of other code can refer to itʼs variables. This surrounding code is the “owner”: But when closures are assigned to other objects, thereʼs more to life than just the surrounding code - esp. note the delegate: this: as in Java, this refers to the instance of the enclosing class where a Closure is defined owner : the enclosing object (this or a surrounding Closure) delegate : by default the same as owner, but changeable for example in a builder or ExpandoMetaClass Monday, June 7, 2010
  • 27. A Review of Closures for Newbies... def postiveOnly(Closure c) { list.each { val -> if(val > 0) c.call(val) } } Oh! And one more thing about closures... Groovy has syntactic sugar which allows a function taking a closure as itʼs final argument can be called with the closure passed after the functions closing paren: Can be called like so: postiveOnly { val -> println “$val is > 0” } And lastly: the default parameter if none is specified is simply “it”: postiveOnly { println “$it is > 0” } Monday, June 7, 2010
  • 28. Finally: some real metaprogramming... String.metaClass.shout = { delegate.toUpperCase(); } println "Groovy".shout() Add a method to a class: And yes, you could even: (but just because you can doesnʼt mean you will) This just shows what a flexible and powerful language groovy is. postiveOnly { println “$it is > 0” } String.metaClass.toUpperCase = { delegate.toLowerCase(); } println "Groovy".toUpperCase() A programming language for grownups. (with a silly name) Monday, June 7, 2010