SlideShare une entreprise Scribd logo
1  sur  28
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

Contenu connexe

Tendances

Tendances (20)

jQuery
jQueryjQuery
jQuery
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da Hood
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
QSpiders - Selenium Webdriver
QSpiders - Selenium WebdriverQSpiders - Selenium Webdriver
QSpiders - Selenium Webdriver
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Clean code
Clean codeClean code
Clean code
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
Selenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | EdurekaSelenium Interview Questions and Answers For Freshers And Experienced | Edureka
Selenium Interview Questions and Answers For Freshers And Experienced | Edureka
 
React js
React jsReact js
React js
 
NestJS
NestJSNestJS
NestJS
 

En vedette (20)

Groovy
GroovyGroovy
Groovy
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Docker
DockerDocker
Docker
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Grails services
Grails servicesGrails services
Grails services
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Command objects
Command objectsCommand objects
Command objects
 
Grails domain classes
Grails domain classesGrails domain classes
Grails domain classes
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Apache tika
Apache tikaApache tika
Apache tika
 
Grails Services
Grails ServicesGrails Services
Grails Services
 
GORM
GORMGORM
GORM
 
Unit testing
Unit testingUnit testing
Unit testing
 

Similaire à MetaProgramming With Groovy: Write Code That Writes Code

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdfvenud11
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptxRaazIndia
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxKunalYadav65140
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailszenMonkey
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answersbestonlinetrainers
 
Multiprocessing.pptx
Multiprocessing.pptxMultiprocessing.pptx
Multiprocessing.pptxMaheshGour5
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance ConceptsEmprovise
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming RailsJustus Eapen
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 

Similaire à MetaProgramming With Groovy: Write Code That Writes Code (20)

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Oops
OopsOops
Oops
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptx
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptx
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And Grails
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
Multiprocessing.pptx
Multiprocessing.pptxMultiprocessing.pptx
Multiprocessing.pptx
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Java basics
Java basicsJava basics
Java basics
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 

Plus de NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Dernier

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Dernier (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

MetaProgramming With Groovy: Write Code That Writes Code

  • 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