SlideShare a Scribd company logo
1 of 45
The Craft of Metaprogramming on JVM
Igor Khotin
E-mail: khotin@gmx.com
Background
● 15+ years in the IT industry
● 10+ years with Java
● Flexible design promoter
After deploymentDeploying...
Meta
Tricks
Code
MetaData
MetaCode
Translators
Domain-Specific Languages
Code Instrumentation
Preprocessors
Translators
Domain-Specific Languages
Code Instrumentation
Preprocessors
LISP
(defmacro setq-reversible (e1 e2 d)
(case d
(:normal (list 'setq e1 e2))
(:backward (list 'setq e2 e1))
(t (error ...))))
bash `backquotes`
JavaScript eval()
Java Motherf***er!
Do you code it?
ClassLoader
Changing the bytecode
Just a hack
Code that live by itself
Backbone for many products
Boilerplate
Meta
Tricks
Code
Annotations
Providing metadata on code
since Java 1.5
Reflection
Know your structure
● Scannotation
● Reflections
Scan and metadata
and now the bytecode time!!!
● Compile-time
● Load-time
● Run-time
Time?
Java Agent
● Ability to modify bytecode
● Not affecting the source
● Transformation handlers
● Special app startup process
● Since Java 1.5
Java Debugging Interface
● Limited ability to reload classes
●
ASM
● Event-based visitors API
● Object-based model API
● Fast
● Anything is possible
● Byte Code Engineering Library
● Object-model API
● Good for static code analysis
● used by findbugs
BCEL
● Java Assistanct
● JBoss subproject
● High-level bytecode manipulation
● Includes simple Java compiler
JAssist
● Java Assistanct
● JBoss subproject
● High-level bytecode manipulation
● Includes simple Java compiler
● Simple
● Slower than ASM
● Limited capabilities compared to ASM
JAssist
● Conceptually high-level
● Manages cross-cutting concerns
● Uses ASM for bytecode-level manipulation
AspectJ
● Introduce Interface (or Superclass)
● Change visibility
● Add new method
● Add new field
● Replace method body
● Merge two classes into one
Class Transformations
● Insert code before/after
● Replace method call
● Replace field access
● Inline method
Method Transformations
● @Before
● @After
● @Around
Aspects
Proxy and Lazy
Meta
Tricks
Code
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Command {
String value();
}
Command
@Command("hi")
public class Hi {
public void exec() {
System.out.println(this.getClass().getName());
System.out.println("Hello annotations!");
}
}
Hi
Reflections reflections = new Reflections("meta");
Set<Class<?>> annotated = reflections
.getTypesAnnotatedWith(Command.class);
for(Class c: annotated) {
Command ca = (Command)c.getAnnotation(
Command.class);
System.out.println("[" + c.getSimpleName()
+ "] -> " + ca.value());
}
Reflections
Class commandClass = map.get(cmd);
Object command = commandClass.newInstance();
Method exec = command.getClass().getMethod(“exec”);
exec.invoke(command);
Reflection
public Class enhance(Class target) {
ClassPool cp = new ClassPool(true);
CtClass ctSuper = cp.get(target.getName());
CtClass ctClass = cp.makeClass("meta.InfectedClass");
ctClass.setSuperclass(ctSuper);
CtMethod execMethod = CtNewMethod.make(
"public void exec() {System.out.print("[ENHANCED] ");super.exec();}",
ctClass);
ctClass.addMethod(execMethod);
ctClass.writeFile();
return ctClass.toClass();
}
JAssist
Eval.me( '2 + 2' )
Groovy eval()
def list = ['Java', 'Groovy', 'Scala']
LanguageList() {
def mc = new ExpandoMetaClass(LanguageList, false, true)
mc.initialize()
this.metaClass = mc
}
def methodMissing(String name, args) {
// Intercept method that starts with find.
if (name.startsWith("find")) {
def result = list.find { it == name[4..-1] }
// Add new method to class with metaClass.
this.metaClass."$name" = {-> result + "[cache]" }
result
} else {
throw new MissingMethodException(
name, this.class, args)
}
}
Groovy missing method
Questions?
Igor Khotin
E-mail: khotin@gmx.com
Blog: www.ikhotin.com
Twitter: chaostarter

More Related Content

What's hot

In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
myrajendra
 

What's hot (20)

Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Java8
Java8Java8
Java8
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
Java 8 – completion stage
Java 8 – completion stageJava 8 – completion stage
Java 8 – completion stage
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapJava.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmap
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Plpgsql internals
Plpgsql internalsPlpgsql internals
Plpgsql internals
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
 

Viewers also liked

Architecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web AppsArchitecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web Apps
Rasheed Waraich
 

Viewers also liked (20)

Big data for everyone
Big data for everyoneBig data for everyone
Big data for everyone
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascript
 
Tech Talks Microservices
Tech Talks MicroservicesTech Talks Microservices
Tech Talks Microservices
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring Boot
 
Microservices with Spring
Microservices with SpringMicroservices with Spring
Microservices with Spring
 
introduce to spring cloud
introduce to spring cloudintroduce to spring cloud
introduce to spring cloud
 
Next-gen OData/ui5 microservices with Spring Boot
Next-gen OData/ui5 microservices with Spring BootNext-gen OData/ui5 microservices with Spring Boot
Next-gen OData/ui5 microservices with Spring Boot
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
Microservices with Spring Cloud
Microservices with Spring CloudMicroservices with Spring Cloud
Microservices with Spring Cloud
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST API Best (Recommended) Practices
REST API Best (Recommended) Practices
 
Microservices with spring boot
Microservices  with spring bootMicroservices  with spring boot
Microservices with spring boot
 
The Fintechs
The FintechsThe Fintechs
The Fintechs
 
Architecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web AppsArchitecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web Apps
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!
 
Spring cloud for microservices architecture
Spring cloud for microservices architectureSpring cloud for microservices architecture
Spring cloud for microservices architecture
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
 
Divide and Conquer: Easier Continuous Delivery using Micro-Services
Divide and Conquer: Easier Continuous Delivery using Micro-ServicesDivide and Conquer: Easier Continuous Delivery using Micro-Services
Divide and Conquer: Easier Continuous Delivery using Micro-Services
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Microservices with Spring and Cloud Foundry
Microservices with Spring and Cloud FoundryMicroservices with Spring and Cloud Foundry
Microservices with Spring and Cloud Foundry
 

Similar to The craft of meta programming on JVM

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
Ahasan Habib
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Howard Lewis Ship
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
tcaesvk
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Volha Banadyseva
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
bwullems
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Victor Rentea
 

Similar to The craft of meta programming on JVM (20)

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
React native
React nativeReact native
React native
 
Code Difference Visualization by a Call Tree
Code Difference Visualization by a Call TreeCode Difference Visualization by a Call Tree
Code Difference Visualization by a Call Tree
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
1- java
1- java1- java
1- java
 
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
 
Short Lightening Talk
Short Lightening TalkShort Lightening Talk
Short Lightening Talk
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 

More from Igor Khotin (8)

Gradle - time for another build
Gradle - time for another buildGradle - time for another build
Gradle - time for another build
 
WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)WDB005.1 - JavaScript for Java Developers (Lecture 1)
WDB005.1 - JavaScript for Java Developers (Lecture 1)
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
 
Business value in game development
Business value in game developmentBusiness value in game development
Business value in game development
 
Cassandra Prophecy
Cassandra ProphecyCassandra Prophecy
Cassandra Prophecy
 
Gradle - next generation of build tools
Gradle - next generation of build toolsGradle - next generation of build tools
Gradle - next generation of build tools
 
XML Magic
XML MagicXML Magic
XML Magic
 
Igor Khotin - Domain Specific Languages
Igor Khotin - Domain Specific LanguagesIgor Khotin - Domain Specific Languages
Igor Khotin - Domain Specific Languages
 

Recently uploaded

Recently uploaded (20)

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

The craft of meta programming on JVM