在kotlinc的jar输出中包含反射库

Bas*_*ani 4 kotlin kotlinc

我正在尝试将反射库包含在示例jar中,但无法使其工作:

$ kotlinc hello.kt -d hello.jar
$ java -jar hello.jar
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
Run Code Online (Sandbox Code Playgroud)

缺少运行时库,所以让我们添加它:

$ 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
Run Code Online (Sandbox Code Playgroud)

现在包含运行时库,但缺少反射库,所以让我们指定kotlin主目录:

$ 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
Run Code Online (Sandbox Code Playgroud)

反射库仍然不包括在内.kotlinc帮助列出一个' -no-reflect'选项,所以我假设在设置' -include-runtime' 时默认情况下应该包含反射库,但似乎并非如此.

Ale*_*lov 6

目前,该-include-runtime选项仅包括kotlin-stdlib生成的jar 的标准Kotlin库().你是对的kotlin-reflect,除非-no-reflect指定了选项,否则还应该包含反射库().我在跟踪器中创建了一个问题:https://youtrack.jetbrains.com/issue/KT-17344

问题解决之前:如果您正在寻找一种仅在您的机器上运行已编译程序的方法,我建议您将应用程序编译到目录而不是jar,然后使用该kotlin命令运行主类.

kotlinc hello.kt -d output
kotlin -cp output hello.HelloKt
Run Code Online (Sandbox Code Playgroud)

如果您计划将程序分发给其他用户,我建议使用正确的构建系统,如Maven或Gradle,并指定kotlin-stdlib/ kotlin-reflect作为正确的依赖项,而不是将它们与您的应用程序一起捆绑在单个jar中.