SlideShare a Scribd company logo
1 of 54
Download to read offline
IvAn LOpez MartIn @ilopmar
Metaprogramming
with Groovy
Iván Lopez Martín @ilopmar
I work at Kaleidos
Using Groovy/Grails since 4 years
Creator of www.bokzuy.com
Developed some Grails plugins: Postgreslq-Extensions,
Slug-Generator, Ducksboard-API,...
Usual Suspect of Madrid-GUG (Groovy User Group)
Who am I?
2/54
- A dynamic language like Groovy allows to "delay" to runtime some
checks that are usually performed during the compilation.
- Add new properties, methods and behaviour during runtime.
- Wide range of applicability:
- DSLs
- Builders
- Advanced logging, tracing, debugging & profiling
- Allow organize the codebase better
- That's why we can talk about Metaprogramming in Groovy.
Groovy is Dynamic
3/54
What is
Metaprogramming?
From Wikipedia:
Metaprogramming is the writing of computer programs that
write or manipulate other programs (or themselves) as their
data, or that do part of the work at compile time that would
otherwise be done at runtime.
“Writing code that writes code”
What is Metaprogramming?
5/54
Runtime
Metaprogramming
- Groovy provides this capability through the Meta-Object Protocol
(MOP).
- We can use MOP to invoke methods dynamically and also synthesize
classes and methods on the fly.
Runtime Metaprogramming
7/54
Groovy
Groovy
Java
Java
MOP
What is the Meta Object Protocol (MOP)?
8/54
Intercepting methods
using MOP
- Classes compiled by Groovy implements GroovyObject interface.
- We can implement GroovyInterceptable to hook into the execution
process.
- When implementing invokeMethod(), it is called for every method
(existing and nonexisting).
Groovy Interceptable
10/54
GroovyInterceptable example
11/54
GroovyInterceptable example (II)
12/54
- Groovy maintains a meta class of type MetaClass for each class.
- Maintains a collection of all methods and properties of A.
- If we can't modify the class source code or if it's a Java class we can
modify the meta-class.
- We can intercept methods by implementing the invokeMethod()
method on the MetaClass.
Intercepting methods using MetaClass
13/54
MetaClass example
14/54
MOP
Method Injection
- In Groovy we can “open” a class at any time.
- Method Injection at code-writing time, we know the names of
methods we want to add.
- Different techniques:
- MetaClass
- Categories
- Extensions
- Mixins
MOP Method Injection
16/54
- MetaClassImpl: Default meta class, it's used in the vast majority of
case.
- ExpandoMetaClass: allow the addition or replacement of methods,
properties and constructors on the fly.
- ProxyMetaClass: Can decorate a meta class with interception
capabilities.
- Other meta classes used internally and for testing.
MetaClass
17/54
Adding methods using MetaClass
18/54
Adding properties using MetaClass
19/54
* Note: This is only true for Groovy.
In Grails all MetaClass are ExpandoMetaClass.
Thank you Burt Beckwith for the clarification
Adding constructor using MetaClass
20/54
Overriding methods using MetaClass
21/54
Overriding methods using MetaClass
22/54
- Changes made to a MetaClass are “persistent” and hard to revert.
- Categories are useful to change the meta class in a confined small
piece of code.
- A category can alter a class’ MetaClass.
- The MOP is modified in the closure and after the closure execution
is reset to its old state.
- Category classes are no special.
Categories
23/54
Categories example
Categories example (II)
25/54
Categories example (II)
26/54
Categories example (II)
27/54
- JAR file with classes that provide extra methods to other classes.
- It also has to contain a meta-information file
- Add the JAR to the classpath to enhance the classes.
- The extension methods needs to be public and static.
Extension modules
28/54
Extension modules example
29/54
- A mixin allow “bring in” or “mix in” implementations from multiple
classes.
- Groovy first call the mixed-in class.
- Mix multiple classes. The last added mixin takes precedence.
- Override a method of a previous Mixin but not methods in the meta
class.
- Mixins cannot easily be un-done.
Mixins
30/54
Mixins example
31/54
MOP
Method Synthesis
- Dynamically figure out the behaviour for methods upon invocation.
- A synthesized method may not exist as a separate method until we
call it.
- invokeMethod, methodMissing and propertyMissing.
- “Intercept, Cache, Invoke” pattern.
MOP Method Synthesis
33/54
Check for methods and properties
34/54
MOP Instances Synthesis
35/54
MethodMissing example
36/54
MethodMissing example
37/54
MethodMissing example
38/54
Compile-time
Metaprogramming
- Advanced feature.
- Analyze and modify a program’sstructure at compile time.
- Cross-cutting features:
- Inspect classes for thread safety
- Log messages
- Perform pre- and postcheck operations
all without explicitly modifying the source code.
- We write code that generates bytecode or gets involved during the
bytecode generation.
Compile-time Metaprogramming
40/54
- AST: Abstract Syntax Tree
- During compilation the AST is transformed
- Hook into different phases to change the final byte-code.
- Initialization, Parsing, Conversion, Semantic analysis,
Canonicalization, Instruction selection, Class generation, Output,
Finalization.
AST and Compilation
41/54
- Groovy provides out-of-the-box a lot of AST Transformations
- @EqualsAndHashCode, @ToString, @TuppleConstructor,
@Canonical, @Grab, @Immutable, @Delegate, @Singleton,
@Category, @Log4j, @CompileStatic, @TypeChecked,
@Synchronized...
Groovy AST Transformations
42/54
Global
AST Transformations
- There's no need to annotate anything.
- Applied to every single source unit during compilation.
- Can be applied to any phase in the compilation.
- Need a metadata file into the JAR file
(META-INF/services/org.codehaus.groovy.transform.
ASTTransformation)
- Grails uses Global Transformations intensively for example in
GORM.
Global AST Transformations
44/54
Local
AST Transformations
- Annotate the code and only applied to that code.
- Easy to debug.
- No need to create metadata file in a jar.
- Steps: Define an interface, Define the AST transformation, Enjoy!
Local AST Transformations
46/54
Local AST Transformation example
47/54
Local AST Transformation example
Local AST Transformation example
- Most of us are not Groovy Commiters, so how do we create the
necessary nodes for our AST Transformation.
- Check de documentation:
http://groovy.codehaus.org/api/org/codehaus/groovy/ast/ASTNode
.html
- Use an IDE
- Use GroovyConsole and open Groovy AST Browser (CTRL + T)
Creating AST nodes. What?
50/54
- Yes. We can use AstBuilder
- buildFromSpec: Provides a DSL for the ClassNode objects
- buildFromString: Creates the AST nodes from a String with the
code.
- buildFromCode: We write directly the source code and the builder
returns the AST.
Is there an easy way?
51/54
Recap:
Why we should use
all of this?
- Groovy provides meta-programming features out-of-the-box, it's a
pity not using them.
- Metaprogramming is easy to use and it's very powerful.
- We can write better code.
- We can add a lot of behaviour to our code in an easy way.
- We're Groovy developers and we need to take advantage of all its
power.
- Because, Groovy it's groovy.
Why we should use all of this?
53/54
http://lopezivan.blogspot.comhttp://lopezivan.blogspot.com
@ilopmar@ilopmar
https://github.com/lmivanhttps://github.com/lmivan
Iván López MartínIván López Martín
lopez.ivan@gmail.comlopez.ivan@gmail.com
Talk Survey:Talk Survey:
http://kcy.me/11lvbhttp://kcy.me/11lvb
Thank you!
http://kaleidos.net/4B0082http://kaleidos.net/4B0082

More Related Content

What's hot

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
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails introMiguel Pastor
 
Embedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationEmbedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationPaolo Predonzani
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationswalkmod
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseAndrew Eisenberg
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentSchalk Cronjé
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageHoat Le
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank WierzbickiJython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank Wierzbickifwierzbicki
 
Running Pharo on the GemStone VM
Running Pharo on the GemStone VMRunning Pharo on the GemStone VM
Running Pharo on the GemStone VMESUG
 
Moldable meta-models for Moose
Moldable meta-models for MooseMoldable meta-models for Moose
Moldable meta-models for MooseESUG
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and PythonAndreas Schreiber
 

What's hot (20)

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
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
 
Embedding Groovy in a Java Application
Embedding Groovy in a Java ApplicationEmbedding Groovy in a Java Application
Embedding Groovy in a Java Application
 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformations
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Introduction to jython
Introduction to jythonIntroduction to jython
Introduction to jython
 
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank WierzbickiJython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
 
JVM
JVMJVM
JVM
 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Running Pharo on the GemStone VM
Running Pharo on the GemStone VMRunning Pharo on the GemStone VM
Running Pharo on the GemStone VM
 
Moldable meta-models for Moose
Moldable meta-models for MooseMoldable meta-models for Moose
Moldable meta-models for Moose
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
 

Similar to Metaprogramming with Groovy

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
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming RailsJustus Eapen
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopMax Kleiner
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdfvenud11
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
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
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
walkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 
33rd degree talk: open and automatic coding conventions with walkmod
33rd degree talk: open and automatic coding conventions with walkmod33rd degree talk: open and automatic coding conventions with walkmod
33rd degree talk: open and automatic coding conventions with walkmodwalkmod
 

Similar to Metaprogramming with Groovy (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
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_Workshop
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Golang for OO Programmers
Golang for OO ProgrammersGolang for OO Programmers
Golang for OO Programmers
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
getting-your-groovy-on
getting-your-groovy-ongetting-your-groovy-on
getting-your-groovy-on
 
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...
 
Puppet camp amsterdam
Puppet camp amsterdamPuppet camp amsterdam
Puppet camp amsterdam
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
walkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventions
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
 
Webpack: from 0 to 2
Webpack: from 0 to 2Webpack: from 0 to 2
Webpack: from 0 to 2
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Greach 2015 Spock workshop
Greach 2015 Spock workshopGreach 2015 Spock workshop
Greach 2015 Spock workshop
 
33rd degree talk: open and automatic coding conventions with walkmod
33rd degree talk: open and automatic coding conventions with walkmod33rd degree talk: open and automatic coding conventions with walkmod
33rd degree talk: open and automatic coding conventions with walkmod
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 

More from Iván López Martín

SalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersSalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersIván López Martín
 
CommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersCommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersIván López Martín
 
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfVoxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfIván López Martín
 
VMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootVMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootIván López Martín
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewayIván López Martín
 
Codemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootCodemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootIván López Martín
 
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3Iván López Martín
 
Construyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMConstruyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMIván López Martín
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTIván López Martín
 
Codemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautCodemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautIván López Martín
 
JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!Iván López Martín
 
JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3Iván López Martín
 
JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3Iván López Martín
 
Developing Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEADeveloping Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEAIván López Martín
 
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaCommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaIván López Martín
 
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Iván López Martín
 
Greach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsGreach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsIván López Martín
 
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youVoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youIván López Martín
 
JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!Iván López Martín
 
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteCrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteIván López Martín
 

More from Iván López Martín (20)

SalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 TestcontainersSalmorejoTech 2024 - Spring Boot <3 Testcontainers
SalmorejoTech 2024 - Spring Boot <3 Testcontainers
 
CommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 TestcontainersCommitConf 2024 - Spring Boot <3 Testcontainers
CommitConf 2024 - Spring Boot <3 Testcontainers
 
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdfVoxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
Voxxed Days CERN 2024 - Spring Boot <3 Testcontainers.pdf
 
VMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring BootVMware - Testcontainers y Spring Boot
VMware - Testcontainers y Spring Boot
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
 
Codemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring BootCodemotion Madrid 2023 - Testcontainers y Spring Boot
Codemotion Madrid 2023 - Testcontainers y Spring Boot
 
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3CommitConf 2023 - Spring Framework 6 y Spring Boot 3
CommitConf 2023 - Spring Framework 6 y Spring Boot 3
 
Construyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVMConstruyendo un API REST con Spring Boot y GraalVM
Construyendo un API REST con Spring Boot y GraalVM
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoT
 
Codemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con MicronautCodemotion Madrid 2020 - Serverless con Micronaut
Codemotion Madrid 2020 - Serverless con Micronaut
 
JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!JConf Perú 2020 - ¡Micronaut en acción!
JConf Perú 2020 - ¡Micronaut en acción!
 
JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3JConf Perú 2020 - Micronaut + GraalVM = <3
JConf Perú 2020 - Micronaut + GraalVM = <3
 
JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3JConf México 2020 - Micronaut + GraalVM = <3
JConf México 2020 - Micronaut + GraalVM = <3
 
Developing Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEADeveloping Micronaut Applications With IntelliJ IDEA
Developing Micronaut Applications With IntelliJ IDEA
 
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfectaCommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
CommitConf 2019 - Micronaut y GraalVm: La combinación perfecta
 
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
Codemotion Madrid 2019 - ¡GraalVM y Micronaut: compañeros perfectos!
 
Greach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut ConfigurationsGreach 2019 - Creating Micronaut Configurations
Greach 2019 - Creating Micronaut Configurations
 
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet youVoxxedDays Bucharest 2019 - Alexa, nice to meet you
VoxxedDays Bucharest 2019 - Alexa, nice to meet you
 
JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!JavaDay Lviv 2019 - Micronaut in action!
JavaDay Lviv 2019 - Micronaut in action!
 
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerteCrossDvlup Madrid 2019 - Alexa, encantado de conocerte
CrossDvlup Madrid 2019 - Alexa, encantado de conocerte
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 

Metaprogramming with Groovy

  • 1. IvAn LOpez MartIn @ilopmar Metaprogramming with Groovy
  • 2. Iván Lopez Martín @ilopmar I work at Kaleidos Using Groovy/Grails since 4 years Creator of www.bokzuy.com Developed some Grails plugins: Postgreslq-Extensions, Slug-Generator, Ducksboard-API,... Usual Suspect of Madrid-GUG (Groovy User Group) Who am I? 2/54
  • 3. - A dynamic language like Groovy allows to "delay" to runtime some checks that are usually performed during the compilation. - Add new properties, methods and behaviour during runtime. - Wide range of applicability: - DSLs - Builders - Advanced logging, tracing, debugging & profiling - Allow organize the codebase better - That's why we can talk about Metaprogramming in Groovy. Groovy is Dynamic 3/54
  • 5. From Wikipedia: Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. “Writing code that writes code” What is Metaprogramming? 5/54
  • 7. - Groovy provides this capability through the Meta-Object Protocol (MOP). - We can use MOP to invoke methods dynamically and also synthesize classes and methods on the fly. Runtime Metaprogramming 7/54
  • 8. Groovy Groovy Java Java MOP What is the Meta Object Protocol (MOP)? 8/54
  • 10. - Classes compiled by Groovy implements GroovyObject interface. - We can implement GroovyInterceptable to hook into the execution process. - When implementing invokeMethod(), it is called for every method (existing and nonexisting). Groovy Interceptable 10/54
  • 13. - Groovy maintains a meta class of type MetaClass for each class. - Maintains a collection of all methods and properties of A. - If we can't modify the class source code or if it's a Java class we can modify the meta-class. - We can intercept methods by implementing the invokeMethod() method on the MetaClass. Intercepting methods using MetaClass 13/54
  • 16. - In Groovy we can “open” a class at any time. - Method Injection at code-writing time, we know the names of methods we want to add. - Different techniques: - MetaClass - Categories - Extensions - Mixins MOP Method Injection 16/54
  • 17. - MetaClassImpl: Default meta class, it's used in the vast majority of case. - ExpandoMetaClass: allow the addition or replacement of methods, properties and constructors on the fly. - ProxyMetaClass: Can decorate a meta class with interception capabilities. - Other meta classes used internally and for testing. MetaClass 17/54
  • 18. Adding methods using MetaClass 18/54
  • 19. Adding properties using MetaClass 19/54 * Note: This is only true for Groovy. In Grails all MetaClass are ExpandoMetaClass. Thank you Burt Beckwith for the clarification
  • 20. Adding constructor using MetaClass 20/54
  • 21. Overriding methods using MetaClass 21/54
  • 22. Overriding methods using MetaClass 22/54
  • 23. - Changes made to a MetaClass are “persistent” and hard to revert. - Categories are useful to change the meta class in a confined small piece of code. - A category can alter a class’ MetaClass. - The MOP is modified in the closure and after the closure execution is reset to its old state. - Category classes are no special. Categories 23/54
  • 28. - JAR file with classes that provide extra methods to other classes. - It also has to contain a meta-information file - Add the JAR to the classpath to enhance the classes. - The extension methods needs to be public and static. Extension modules 28/54
  • 30. - A mixin allow “bring in” or “mix in” implementations from multiple classes. - Groovy first call the mixed-in class. - Mix multiple classes. The last added mixin takes precedence. - Override a method of a previous Mixin but not methods in the meta class. - Mixins cannot easily be un-done. Mixins 30/54
  • 33. - Dynamically figure out the behaviour for methods upon invocation. - A synthesized method may not exist as a separate method until we call it. - invokeMethod, methodMissing and propertyMissing. - “Intercept, Cache, Invoke” pattern. MOP Method Synthesis 33/54
  • 34. Check for methods and properties 34/54
  • 40. - Advanced feature. - Analyze and modify a program’sstructure at compile time. - Cross-cutting features: - Inspect classes for thread safety - Log messages - Perform pre- and postcheck operations all without explicitly modifying the source code. - We write code that generates bytecode or gets involved during the bytecode generation. Compile-time Metaprogramming 40/54
  • 41. - AST: Abstract Syntax Tree - During compilation the AST is transformed - Hook into different phases to change the final byte-code. - Initialization, Parsing, Conversion, Semantic analysis, Canonicalization, Instruction selection, Class generation, Output, Finalization. AST and Compilation 41/54
  • 42. - Groovy provides out-of-the-box a lot of AST Transformations - @EqualsAndHashCode, @ToString, @TuppleConstructor, @Canonical, @Grab, @Immutable, @Delegate, @Singleton, @Category, @Log4j, @CompileStatic, @TypeChecked, @Synchronized... Groovy AST Transformations 42/54
  • 44. - There's no need to annotate anything. - Applied to every single source unit during compilation. - Can be applied to any phase in the compilation. - Need a metadata file into the JAR file (META-INF/services/org.codehaus.groovy.transform. ASTTransformation) - Grails uses Global Transformations intensively for example in GORM. Global AST Transformations 44/54
  • 46. - Annotate the code and only applied to that code. - Easy to debug. - No need to create metadata file in a jar. - Steps: Define an interface, Define the AST transformation, Enjoy! Local AST Transformations 46/54
  • 47. Local AST Transformation example 47/54
  • 50. - Most of us are not Groovy Commiters, so how do we create the necessary nodes for our AST Transformation. - Check de documentation: http://groovy.codehaus.org/api/org/codehaus/groovy/ast/ASTNode .html - Use an IDE - Use GroovyConsole and open Groovy AST Browser (CTRL + T) Creating AST nodes. What? 50/54
  • 51. - Yes. We can use AstBuilder - buildFromSpec: Provides a DSL for the ClassNode objects - buildFromString: Creates the AST nodes from a String with the code. - buildFromCode: We write directly the source code and the builder returns the AST. Is there an easy way? 51/54
  • 52. Recap: Why we should use all of this?
  • 53. - Groovy provides meta-programming features out-of-the-box, it's a pity not using them. - Metaprogramming is easy to use and it's very powerful. - We can write better code. - We can add a lot of behaviour to our code in an easy way. - We're Groovy developers and we need to take advantage of all its power. - Because, Groovy it's groovy. Why we should use all of this? 53/54
  • 54. http://lopezivan.blogspot.comhttp://lopezivan.blogspot.com @ilopmar@ilopmar https://github.com/lmivanhttps://github.com/lmivan Iván López MartínIván López Martín lopez.ivan@gmail.comlopez.ivan@gmail.com Talk Survey:Talk Survey: http://kcy.me/11lvbhttp://kcy.me/11lvb Thank you! http://kaleidos.net/4B0082http://kaleidos.net/4B0082