如何在运行时编译和使用 Kotlin 代码?

How to compile and use Kotlin code in runtime?

我正在尝试创建一个 Kotlin Vert.x language support module and I need a way to compile Kotlin files and load the results with a ClassLoader. I've tried using kotlin-compiler library and found K2JVMCompiler class, but it seems to support only command-line-style arguments with its exec method. Is there a way to compile a Kotlin file in runtime (possibly without having to save and read .class files) and immediately load the generated classes? (Kind of like Groovy。)如果没有,您是否有任何有用的编译器参数建议或几乎任何建议?

这感觉就像 XY Problem。您想知道如何动态编译 Kotlin,以便您可以更轻松地从 Kotlin 源文件而不是编译代码中使用 Vert.x by 运行ning。但实际上 Vert.x 使用的推荐路径是创建一段简单的代码,在 compiled 代码中部署你的 Verticle。

在问题中,您的 link 语言支持在路径 "vertx.io/vertx2/language_support.html" 中说 Vert.x 2;这与 Vert.x 中现在的做法不同 3. 我认为您正在将两个想法合二为一。首先,Vert.x 3 希望您从源文件中获取 运行 Java/Kotlin 文件( 事实并非如此;那是 Vert.x 2 他们放弃的东西对于编译语言),其次你需要自定义语言支持(你不需要)。

您应该尝试使用 Vert.x 3 by 运行ning 编译代码。 为此,构建您的 类 和 运行 你自己的 main()deploys a verticle programatically。您的代码很简单:

import io.vertx.core.Vertx

fun main(args: Array<String>) {
    val vertx = Vertx.vertx()
    vertx.deployVerticle(SomeVerticleOfMine())
}

或者,docs for running and deploying from the command-line 说:

Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going!

而且实际上它确实只是用于原型设计和快速测试,而且它并不比让你的 IDE 做同样的事情和从编译的 类 中 运行ning 更快.您还可以使用 IDE 的调试功能,这些功能非常有价值。

有关将 Kotlin 与 Vert.x 一起使用的一些帮助程序库,请查看这些选项:

有一个full sample project of running Vert.x + Kovert (specifically start with the App class). You can look at the code of Kovert to do your own similar work of starting and running Vert.x nicely, with Promises or however you wish. The docs for Kovert have links to code for starting Vertx and also starting a Verticle to use Vert.x-Web, so more sample code you can read. But it helps to understand Injekt (light-weight dependency registry), Kovenant (promises library), and Klutter configuration injection可以理解完整的示例。

其他快速说明、Vert.x 有对其他语言的代码生成支持,但由于您可以直接调用所有 Java 版本,因此它不也需要支持 Kotlin。

Kotlin 1.1 带有 javax.script (JSR-223) 支持,这意味着您可以像 JavaScript 和 Nashorn 一样将它用作脚本引擎。