How to call Kotlin compiler to compile some Kotlin source files from Java?


#1

I want to call Kotlin compiler to comiple some Kotlin source files from Java, how to do it?

I mean to invoke some classes and functions, not calling command line from Java.


#2

Have a look at the sources of build tools that run Kotlin:

For example, here’s what Maven does: https://github.com/JetBrains/kotlin/blob/master/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojoBase.java


#3

It seems Kotlin compiler can only accept source dirs and output the generated bytecode to some dirs. Is it possible to pass some kotlin files and get the generate bytecode directly?


#4

Yes, you can add individual source files instead of dirs. This does not apply to outputs, because we generate more class files than there're input source files (you can declare many classes in a source file).


#5

Can we get generated bytecode back directly, instead of .class files?


#6

Yes, have a look at how class files are written


#7

Thank you!