SlideShare a Scribd company logo
MetaProgramming With Groovy
Agenda
What is MetaProgramming
MetaProgramming in Groovy
Simple Demo
Objects In Groovy
MOP Method Injection
MOP Method Synthesis
Method Mixins
What is MetaProgramming
From Wikipedia:
Metaprogramming is the writing of computer programs that
write or manipulate other programs (or themselves) as their
data.
“Writing code that writes code”
MetaProgramming in groovy
● 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
MetaProgramming in groovy
MetaProgramming in groovy
In Groovy Language, every object has an object of MetaClass class with name
metaClass. This metaClass object is responsible for holding all the information
related to that object. Whenever you perform any operation on that object,
Groovy’s dispatch mechanism routes the call through that Metaclass
object(metaClass). So if you want to change the behaviour of any object/class,
you will have to alter the MetaClass object attached to that class/object, and it will
alter the behaviour of that class/object at run time.
Metaprogramming is to extend the syntax and vocabulary of program at runtime
as we please dynamically that is exactly what metaprogramming really is all about
Gradle and grails are great example of metaprogramming in groovy
Demo of MetaProgramming
Integer.metaClass.isEven = { -> // only (->) sign indicates that isEven() method is
no argument method
println delegate%2 == 0
}
6.isEven()
7.isEven()
Demo of MetaProgramming
When you inject a method into class the injection process hands that delegate to
closure and delegate is the instance on which method is going to run .
We can say delegate is reference of that object who is invoking that isEven()
method.
Within a closure it is meaningless to use this because this refers to closures
Delegate represents the contextual object in which code is running
MetaProgramming in groovy
Whenever we call a method of class/object, it first gets information of that object
from metaClass attached to it, and then calls the appropriate method. In above
program we are asking Integer.metaClass, that there is an isEven() method in
integer class, whose definition is followed by it. Now when we will call
“anyInteger.isEven()”, it will excute isEven() method and will return true/false
accordingly, e.g.
The method does not add up in jvm but is called from meta class
MetaPogramming does kill performance but it makes up for that with the dnamic
features
Objects in Groovy
● Plain Old Java Objects (POJOs) - instances of regular java objects created on
JVM.
● Plain Old Groovy Objects (POGOs) - subclasses of GroovyObject. An
interface defined as follows.
public interface GroovyObject {
Object invokeMethod(String name, Object args);
Object getProperty(String property);
Object setProperty(String property, Object newValue);
MetaClass getMetaClass();
void setMetaClass(MetaClass metaclass);
}
Objects in Groovy
Groovy Interceptors - subclasses of GroovyInterceptable
● public interface GroovyInterceptable extends GroovyObject {}
With a POGO it is simple. You need to call its setMetaClass method and a
reference to this metaclass is stored within the object. With POJO this is
impossible - they are not designed to store a metaclass reference. For this reason
Groovy maintains an application wide MetaClassRegistry which maps
java.lang.Classes to metaclasses.
http://igor.kupczynski.info/2013/12/07/groovy-method-resolution.html
GroovyObject in Action
All Groovy classes implement this interface
class Person
{
def name
def sleep() { println "sleeping"}
}
>> groovyc Person.groovy
>> javap –public Person
Intercepting methods using MetaClass
● Groovy maintains a meta class of type MetaClass for each class.
● 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.
Demo Of Invoke Method
This demo shows the working of invoke Method which is quite similar of how after
before and around advices work
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
Capability of Injection
● Adding properties using MetaClass
● Adding constructor using MetaClass
● Overriding methods using MetaClass
}
Injecting static method
Integer.metaClass.static.isEven = { number ->
number%2 == 0
}
Integer.isEven(1) // false
Integer.isEven(2) // true
Injecting to a instance
isEven() method is added to all the Integer objects, if we want to add isEven() in a
particular object only then we have to use that object reference
Integer aNumber = 9
aNumber.metaClass.isEven = { ->
delegate%2 == 0
}
println aNumber.isEven() // false
println 2.isEven() // will throw MissingMethodException.
Integer.metaClass {
isEven { -> delegate%2 == 0 }
isOdd { -> delegate%2 != 0 }
// other methods
}
println 6.isEven() // true
println 6.isOdd() // false
Add multiple methods
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.
Demo of MethodMissing
Method Mixins
● Inject methods from other types
● Works on classes and interfaces
● Doesn’t not work on instances
● Easier to use than Categories
Demo of Method Mixins
Applications
● Dynamic finders
● Builders
● Custom DSL
● Dependency Injection
● Method injection
● Interceptors
● Generate mock objects for unit testing
MetaClasses in groovy
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 interceptioncapabilities.
● Other meta classes used internally and for testing.
Questions
References
http://groovy-lang.org/metaprogramming.html
http://igor.kupczynski.info/2013/12/07/groovy-method-resolution.html
http://www.slideshare.net/zenMonkey/metaprogramming-techniques-in-groovy-
and-grails
https://www.youtube.com/watch?v=UJhlp5P7Ec0
http://www.slideshare.net/ilopmar/metaprogramming-with-groovy
Thank You
Presented By:- Chetan Khare
For demo project please visit https://github.com/NexThoughts/groovy-
meta-programming

More Related Content

PDF
API Asynchrones en Java 8
PPTX
Whitebox testing of Spring Boot applications
PDF
Workshop 21: React Router
PDF
Arquitetura Node com NestJS
PPTX
世界一わかりやすいClean Architecture release-preview
PDF
Modernization patterns to refactor a legacy application into event driven mic...
PPTX
Redux workshop
PPTX
Cache in API Gateway
API Asynchrones en Java 8
Whitebox testing of Spring Boot applications
Workshop 21: React Router
Arquitetura Node com NestJS
世界一わかりやすいClean Architecture release-preview
Modernization patterns to refactor a legacy application into event driven mic...
Redux workshop
Cache in API Gateway

What's hot (20)

PPTX
RDBMS to NoSQL. An overview.
PDF
#살아있다 #자프링외길12년차 #코프링2개월생존기
PDF
RxJS Operators - Real World Use Cases (FULL VERSION)
PPTX
java 8 new features
PDF
What’s new in grails framework 5?
PDF
Don't Be Mocked by your Mocks - Best Practices using Mocks
PDF
Clean backends with NestJs
PDF
Javascript Design Patterns
PDF
DDD 구현기초 (거의 Final 버전)
PDF
Observables in Angular
PDF
Clean pragmatic architecture @ devflix
PDF
Lambdas and Streams Master Class Part 2
PDF
ドメイン駆動設計入門
PDF
Clean coding-practices
PDF
Getting started with TDD & BDD in C++
PDF
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
PPTX
Strategy pattersn
PDF
slingmodels
PPTX
Java 11 to 17 : What's new !?
PDF
Netflix conductor
RDBMS to NoSQL. An overview.
#살아있다 #자프링외길12년차 #코프링2개월생존기
RxJS Operators - Real World Use Cases (FULL VERSION)
java 8 new features
What’s new in grails framework 5?
Don't Be Mocked by your Mocks - Best Practices using Mocks
Clean backends with NestJs
Javascript Design Patterns
DDD 구현기초 (거의 Final 버전)
Observables in Angular
Clean pragmatic architecture @ devflix
Lambdas and Streams Master Class Part 2
ドメイン駆動設計入門
Clean coding-practices
Getting started with TDD & BDD in C++
Top 1000 Java Interview Questions Includes Spring, Hibernate, Microservices, ...
Strategy pattersn
slingmodels
Java 11 to 17 : What's new !?
Netflix conductor
Ad

Viewers also liked (20)

ODP
PPTX
Introduction to mongo db
PDF
Unit test-using-spock in Grails
PPTX
Java reflection
PPTX
Actors model in gpars
PPTX
MetaProgramming with Groovy
PPT
Grails Controllers
PPTX
Grails services
PPTX
PPTX
Grails with swagger
ODP
Command objects
PPTX
Grails domain classes
PDF
Reactive java - Reactive Programming + RxJava
PDF
Introduction to thymeleaf
PPTX
PPTX
Grails Services
Introduction to mongo db
Unit test-using-spock in Grails
Java reflection
Actors model in gpars
MetaProgramming with Groovy
Grails Controllers
Grails services
Grails with swagger
Command objects
Grails domain classes
Reactive java - Reactive Programming + RxJava
Introduction to thymeleaf
Grails Services
Ad

Similar to Meta Programming in Groovy (20)

PPTX
Metaprogramming with Groovy
PDF
The Next Generation MOP, Jochen Theodorou, GR8Conf 2013
PPTX
Metaprogramming Techniques In Groovy And Grails
PDF
Greach 2014 - Metaprogramming with groovy
PDF
cdac@parag.gajbhiye@groovy metaprogrammning
PPT
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
PPT
Groovy Basics
PDF
Mopping Up With Groovy
PPT
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
PDF
ConFess Vienna 2015 - Metaprogramming with Groovy
PDF
Introduction to Groovy runtime metaprogramming and AST transforms
PDF
Groovy Metaprogramming for Dummies
PDF
GeeCON Prague 2014 - Metaprogramming with Groovy
PPTX
getting-your-groovy-on
PDF
Groovy MOPping
PDF
DSL's with Groovy
PDF
Practical Domain-Specific Languages in Groovy
PDF
Groovy On Trading Desk (2010)
PDF
Oscon Java Testing on the Fast Lane
PDF
Apache Groovy's Metaprogramming Options and You
Metaprogramming with Groovy
The Next Generation MOP, Jochen Theodorou, GR8Conf 2013
Metaprogramming Techniques In Groovy And Grails
Greach 2014 - Metaprogramming with groovy
cdac@parag.gajbhiye@groovy metaprogrammning
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Groovy Basics
Mopping Up With Groovy
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
ConFess Vienna 2015 - Metaprogramming with Groovy
Introduction to Groovy runtime metaprogramming and AST transforms
Groovy Metaprogramming for Dummies
GeeCON Prague 2014 - Metaprogramming with Groovy
getting-your-groovy-on
Groovy MOPping
DSL's with Groovy
Practical Domain-Specific Languages in Groovy
Groovy On Trading Desk (2010)
Oscon Java Testing on the Fast Lane
Apache Groovy's Metaprogramming Options and You

More from NexThoughts Technologies (20)

PDF
PDF
Docker & kubernetes
PDF
Apache commons
PDF
Microservice Architecture using Spring Boot with React & Redux
PDF
Solid Principles
PDF
Introduction to TypeScript
PDF
Smart Contract samples
PDF
My Doc of geth
PDF
Geth important commands
PDF
Ethereum genesis
PPTX
Springboot Microservices
PDF
An Introduction to Redux
PPTX
Google authentication
Docker & kubernetes
Apache commons
Microservice Architecture using Spring Boot with React & Redux
Solid Principles
Introduction to TypeScript
Smart Contract samples
My Doc of geth
Geth important commands
Ethereum genesis
Springboot Microservices
An Introduction to Redux
Google authentication

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Empathic Computing: Creating Shared Understanding
PDF
Electronic commerce courselecture one. Pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation_ Review paper, used for researhc scholars
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Empathic Computing: Creating Shared Understanding
Electronic commerce courselecture one. Pdf
MYSQL Presentation for SQL database connectivity
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
The Rise and Fall of 3GPP – Time for a Sabbatical?

Meta Programming in Groovy

  • 2. Agenda What is MetaProgramming MetaProgramming in Groovy Simple Demo Objects In Groovy MOP Method Injection MOP Method Synthesis Method Mixins
  • 3. What is MetaProgramming From Wikipedia: Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data. “Writing code that writes code”
  • 4. MetaProgramming in groovy ● 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
  • 6. MetaProgramming in groovy In Groovy Language, every object has an object of MetaClass class with name metaClass. This metaClass object is responsible for holding all the information related to that object. Whenever you perform any operation on that object, Groovy’s dispatch mechanism routes the call through that Metaclass object(metaClass). So if you want to change the behaviour of any object/class, you will have to alter the MetaClass object attached to that class/object, and it will alter the behaviour of that class/object at run time. Metaprogramming is to extend the syntax and vocabulary of program at runtime as we please dynamically that is exactly what metaprogramming really is all about Gradle and grails are great example of metaprogramming in groovy
  • 7. Demo of MetaProgramming Integer.metaClass.isEven = { -> // only (->) sign indicates that isEven() method is no argument method println delegate%2 == 0 } 6.isEven() 7.isEven()
  • 8. Demo of MetaProgramming When you inject a method into class the injection process hands that delegate to closure and delegate is the instance on which method is going to run . We can say delegate is reference of that object who is invoking that isEven() method. Within a closure it is meaningless to use this because this refers to closures Delegate represents the contextual object in which code is running
  • 9. MetaProgramming in groovy Whenever we call a method of class/object, it first gets information of that object from metaClass attached to it, and then calls the appropriate method. In above program we are asking Integer.metaClass, that there is an isEven() method in integer class, whose definition is followed by it. Now when we will call “anyInteger.isEven()”, it will excute isEven() method and will return true/false accordingly, e.g. The method does not add up in jvm but is called from meta class MetaPogramming does kill performance but it makes up for that with the dnamic features
  • 10. Objects in Groovy ● Plain Old Java Objects (POJOs) - instances of regular java objects created on JVM. ● Plain Old Groovy Objects (POGOs) - subclasses of GroovyObject. An interface defined as follows. public interface GroovyObject { Object invokeMethod(String name, Object args); Object getProperty(String property); Object setProperty(String property, Object newValue); MetaClass getMetaClass(); void setMetaClass(MetaClass metaclass); }
  • 11. Objects in Groovy Groovy Interceptors - subclasses of GroovyInterceptable ● public interface GroovyInterceptable extends GroovyObject {} With a POGO it is simple. You need to call its setMetaClass method and a reference to this metaclass is stored within the object. With POJO this is impossible - they are not designed to store a metaclass reference. For this reason Groovy maintains an application wide MetaClassRegistry which maps java.lang.Classes to metaclasses. http://igor.kupczynski.info/2013/12/07/groovy-method-resolution.html
  • 12. GroovyObject in Action All Groovy classes implement this interface class Person { def name def sleep() { println "sleeping"} } >> groovyc Person.groovy >> javap –public Person
  • 13. Intercepting methods using MetaClass ● Groovy maintains a meta class of type MetaClass for each class. ● 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.
  • 14. Demo Of Invoke Method This demo shows the working of invoke Method which is quite similar of how after before and around advices work
  • 15. 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
  • 16. Capability of Injection ● Adding properties using MetaClass ● Adding constructor using MetaClass ● Overriding methods using MetaClass }
  • 17. Injecting static method Integer.metaClass.static.isEven = { number -> number%2 == 0 } Integer.isEven(1) // false Integer.isEven(2) // true
  • 18. Injecting to a instance isEven() method is added to all the Integer objects, if we want to add isEven() in a particular object only then we have to use that object reference Integer aNumber = 9 aNumber.metaClass.isEven = { -> delegate%2 == 0 } println aNumber.isEven() // false println 2.isEven() // will throw MissingMethodException.
  • 19. Integer.metaClass { isEven { -> delegate%2 == 0 } isOdd { -> delegate%2 != 0 } // other methods } println 6.isEven() // true println 6.isOdd() // false Add multiple methods
  • 20. 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.
  • 22. Method Mixins ● Inject methods from other types ● Works on classes and interfaces ● Doesn’t not work on instances ● Easier to use than Categories
  • 23. Demo of Method Mixins
  • 24. Applications ● Dynamic finders ● Builders ● Custom DSL ● Dependency Injection ● Method injection ● Interceptors ● Generate mock objects for unit testing
  • 25. MetaClasses in groovy 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 interceptioncapabilities. ● Other meta classes used internally and for testing.
  • 28. Thank You Presented By:- Chetan Khare For demo project please visit https://github.com/NexThoughts/groovy- meta-programming