kotlinkotlinc

Including the reflection library in a jar output by kotlinc


I'm trying to get the reflection lib included in sample jar, but can't get it to work:

$ kotlinc hello.kt -d hello.jar
$ java -jar hello.jar
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics

The runtime lib was missing, so let's add it:

$ kotlinc hello.kt -include-runtime -d hello.jar
$ java -jar hello.jar
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath

Now the runtime lib is included, but the reflection lib is missing, so let's specify kotlin home directory:

$ kotlinc hello.kt -include-runtime -kotlin-home ~/.sdkman/candidates/kotlin/1.1.1 -d hello.jar
$ java -jar hello.jar
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath

Reflection lib is still not included. kotlinc help lists a '-no-reflect' option, so I'm assuming the reflection library should be included by default when '-include-runtime' is set, but this doesn't seem to be the case.


Solution

  • Currently the -include-runtime option only includes the standard Kotlin library (kotlin-stdlib) to the resulting jar. You're right in that the reflection library (kotlin-reflect) should also be included, unless the -no-reflect option is specified. I've created an issue in the tracker: https://youtrack.jetbrains.com/issue/KT-17344

    Until the issue is resolved: if you're looking for a way to run the compiled program on your machine only, I recommend you to compile your application to the directory instead of a jar, and then run the main class with the kotlin command.

    kotlinc hello.kt -d output
    kotlin -cp output hello.HelloKt
    

    If you're planning to distribute the program to other users though, I recommend to use a proper build system like Maven or Gradle and specify kotlin-stdlib/kotlin-reflect as proper dependencies there, instead of bundling them together with your application in the single jar.