Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Ā
How to generate JAR file dynamically compiling Java code in Kotlin
1. How to generate JAR ļ¬le 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),āØ
ļ¬uency (yet another ļ¬uent 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 ļ¬le
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 ļ¬le 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 ļ¬les
to a set of class ļ¬les like JAVAC, but also compile
a Java expression, block, class body or source
ļ¬le 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 ļ¬eld
ByteArrayClassLoader.classes in Janino
using reļ¬ection!@CompileVisitor.kt
11. Create a JAR ļ¬le from the byte
code and dependent classes
Prepare dependent class ļ¬les
@CompileVisitor.kt
Create the compiled class ļ¬le
Get Java byte code using
Class#getResourceAsStream
12. Create a JAR ļ¬le from the byte
code and dependent classes
@CompileVisitor.kt
Setup a manifest
Create a JAR ļ¬le reading class ļ¬les
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 ļ¬le to avoid runtime
failures.