SlideShare a Scribd company logo
1 of 14
How to generate JAR file dynamically
compiling Java code in Kotlin
Mitsunori Komatsu
About me
• Mitsunori Komatsu, 

Software engineer at Treasure Data
• github:komamitsu

msgpack-java

(jackson-dataformat-msgpack),

fluency (yet another fluent logger java)

treasuredata_fdw (with td-client-rust)
Why did I try it?
• First, I developed just a tiny Lisp
interpreter in Kotlin for exercise
• But basically, interpreters aren’t so fast.
So, I tried dynamically compiling Lisp
code to Java byte code
• Finally, I tried outputting those Java
byte code to a JAR file
Where can we see the
source code?
https://github.com/komamitsu/tiny-
kotlin-lisp
How did I do that?
• Convert Lisp AST to Java source code
traversing the tree using Visitor pattern
• Compile the Java source code using
http://janino-compiler.github.io/janino/
• Extract the Java byte code with a bit hack
• Create a JAR file from the byte code and
dependent classes
Convert Lisp AST to Java source code
traversing the tree using Visitor pattern
@CompileVisitor.kt
Nothing special…
Convert Lisp AST to Java source code
traversing the tree using Visitor pattern
@CompileVisitor.kt
Nothing special…
http://janino-compiler.github.io/janino/
With Janino!!
Janino can not only compile a set of source files
to a set of class files like JAVAC, but also compile
a Java expression, block, class body or source
file in memory, load the bytecode and execute it
directly in the same JVM.
Compile the Java source code
Compile the Java source code
and Extract the Java byte code
• It’s really easy to dynamically compile
Java source code and invoke it with
Janino
• But Janino doesn’t provide any API to
get compiled Java byte code…
Compile the Java source code
and Extract the Java byte code
Compile
Extract
Access a hidden field
ByteArrayClassLoader.classes in Janino
using reflection!@CompileVisitor.kt
Create a JAR file from the byte
code and dependent classes
Prepare dependent class files
@CompileVisitor.kt
Create the compiled class file
Get Java byte code using
Class#getResourceAsStream
Create a JAR file from the byte
code and dependent classes
@CompileVisitor.kt
Setup a manifest
Create a JAR file reading class files
Pitfalls
@CompileVisitor.kt
• When writing Kotlin code, it easily has dependencies
with internal Kotlin classes (e.g
kotlin.KotlinNullPointerException). So the classes are
needed to be included in a JAR file to avoid runtime
failures.
Enjoy programming!

More Related Content

What's hot

Ruby an overall approach
Ruby an overall approachRuby an overall approach
Ruby an overall approachFelipe Schmitt
 
Kotlin For Android (at DevFest İzmir 2016)
Kotlin For Android (at DevFest İzmir 2016)Kotlin For Android (at DevFest İzmir 2016)
Kotlin For Android (at DevFest İzmir 2016)Semih Bozdemir
 
The Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineThe Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineFrontech
 
Tutorial for developing SILOptimizer Pass
Tutorial for developing SILOptimizer PassTutorial for developing SILOptimizer Pass
Tutorial for developing SILOptimizer Pass秋 勇紀
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecturesubnesh
 
Making CLI app in ruby
Making CLI app in rubyMaking CLI app in ruby
Making CLI app in rubyHuy Do
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Railsmithunsasidharan
 
Indic threads pune12-akka-actors
Indic threads pune12-akka-actorsIndic threads pune12-akka-actors
Indic threads pune12-akka-actorsIndicThreads
 
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...Codemotion Tel Aviv
 
Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)srigi
 
Architecture diagram of jvm
Architecture diagram of jvmArchitecture diagram of jvm
Architecture diagram of jvmhome
 
Swift language - A fast overview of some features
Swift language - A fast overview of some featuresSwift language - A fast overview of some features
Swift language - A fast overview of some featuresWeverton Timoteo
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architectureatozknowledge .com
 
introduction to java
introduction to javaintroduction to java
introduction to javaAzaz Maverick
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBrian Sam-Bodden
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsAmit Patel
 
JVM Interop - Functional Conf 2019
JVM Interop - Functional Conf 2019JVM Interop - Functional Conf 2019
JVM Interop - Functional Conf 2019Ravindra Jaju
 

What's hot (20)

Byte code jvm
Byte code jvmByte code jvm
Byte code jvm
 
Ruby an overall approach
Ruby an overall approachRuby an overall approach
Ruby an overall approach
 
Kotlin For Android (at DevFest İzmir 2016)
Kotlin For Android (at DevFest İzmir 2016)Kotlin For Android (at DevFest İzmir 2016)
Kotlin For Android (at DevFest İzmir 2016)
 
The Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineThe Real Thing: Java Virtual Machine
The Real Thing: Java Virtual Machine
 
Tutorial for developing SILOptimizer Pass
Tutorial for developing SILOptimizer PassTutorial for developing SILOptimizer Pass
Tutorial for developing SILOptimizer Pass
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Making CLI app in ruby
Making CLI app in rubyMaking CLI app in ruby
Making CLI app in ruby
 
Ruby programming
Ruby programmingRuby programming
Ruby programming
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Indic threads pune12-akka-actors
Indic threads pune12-akka-actorsIndic threads pune12-akka-actors
Indic threads pune12-akka-actors
 
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...
Master the Art of the AST (and Take Control of Your JS!) - Yonatan Mevorach, ...
 
JVM
JVMJVM
JVM
 
Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)
 
Architecture diagram of jvm
Architecture diagram of jvmArchitecture diagram of jvm
Architecture diagram of jvm
 
Swift language - A fast overview of some features
Swift language - A fast overview of some featuresSwift language - A fast overview of some features
Swift language - A fast overview of some features
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architecture
 
introduction to java
introduction to javaintroduction to java
introduction to java
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRuby
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
JVM Interop - Functional Conf 2019
JVM Interop - Functional Conf 2019JVM Interop - Functional Conf 2019
JVM Interop - Functional Conf 2019
 

Similar to How to generate JAR file dynamically compiling Java code in Kotlin

basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragonAyushman Jain
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaAlex Moskvin
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Spring framework
Spring frameworkSpring framework
Spring frameworkAircon Chen
 

Similar to How to generate JAR file dynamically compiling Java code in Kotlin (20)

Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
Jvm
JvmJvm
Jvm
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java goes wild, lesson 1
Java goes wild, lesson 1Java goes wild, lesson 1
Java goes wild, lesson 1
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
In Vogue Dynamic
In Vogue DynamicIn Vogue Dynamic
In Vogue Dynamic
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Java basic
Java basicJava basic
Java basic
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

How to generate JAR file dynamically compiling Java code in Kotlin

  • 1. How to generate JAR file dynamically compiling Java code in Kotlin Mitsunori Komatsu
  • 2. About me • Mitsunori Komatsu, 
 Software engineer at Treasure Data • github:komamitsu
 msgpack-java
 (jackson-dataformat-msgpack),
 fluency (yet another fluent logger java)
 treasuredata_fdw (with td-client-rust)
  • 3. Why did I try it? • First, I developed just a tiny Lisp interpreter in Kotlin for exercise • But basically, interpreters aren’t so fast. So, I tried dynamically compiling Lisp code to Java byte code • Finally, I tried outputting those Java byte code to a JAR file
  • 4. Where can we see the source code? https://github.com/komamitsu/tiny- kotlin-lisp
  • 5. How did I do that? • Convert Lisp AST to Java source code traversing the tree using Visitor pattern • Compile the Java source code using http://janino-compiler.github.io/janino/ • Extract the Java byte code with a bit hack • Create a JAR file from the byte code and dependent classes
  • 6. Convert Lisp AST to Java source code traversing the tree using Visitor pattern @CompileVisitor.kt Nothing special…
  • 7. Convert Lisp AST to Java source code traversing the tree using Visitor pattern @CompileVisitor.kt Nothing special…
  • 8. http://janino-compiler.github.io/janino/ With Janino!! Janino can not only compile a set of source files to a set of class files like JAVAC, but also compile a Java expression, block, class body or source file in memory, load the bytecode and execute it directly in the same JVM. Compile the Java source code
  • 9. Compile the Java source code and Extract the Java byte code • It’s really easy to dynamically compile Java source code and invoke it with Janino • But Janino doesn’t provide any API to get compiled Java byte code…
  • 10. Compile the Java source code and Extract the Java byte code Compile Extract Access a hidden field ByteArrayClassLoader.classes in Janino using reflection!@CompileVisitor.kt
  • 11. Create a JAR file from the byte code and dependent classes Prepare dependent class files @CompileVisitor.kt Create the compiled class file Get Java byte code using Class#getResourceAsStream
  • 12. Create a JAR file from the byte code and dependent classes @CompileVisitor.kt Setup a manifest Create a JAR file reading class files
  • 13. Pitfalls @CompileVisitor.kt • When writing Kotlin code, it easily has dependencies with internal Kotlin classes (e.g kotlin.KotlinNullPointerException). So the classes are needed to be included in a JAR file to avoid runtime failures.