使用 javax.script.ScriptEngineManager 评估 JVM 内的 Kotlin 时出现的问题

Nat*_*nPB 5 jvm eval meta-inf kotlin

我正在尝试使用 Java 脚本 API 评估 JVM 内的 Kotlin 代码。

try {
    ScriptEngineManager().getEngineByExtension("kts").let {
        it.eval("val f: (CommandContext.()->Any?) = {\n${this.args.joinToString(" ")}\n}; return f") as (CommandContext.()->Any?)
    }().let { embed.setDescription(it.toString()) }
} catch (ex: Exception) {
    embed.setColor(Color.RED)
    embed.setDescription(StringWriter().also { ex.printStackTrace(PrintWriter(it)) }.toString())
}
Run Code Online (Sandbox Code Playgroud)

但是...ScriptEngineManager().getEngineByExtension("kts")返回给我一个空值。我已经添加了META-INF/services文件:

文件名:javax.script.ScriptEngineFactory

文件内容:org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory

根据 JetBrains 的说法,它应该可以工作:https://github.com/JetBrains/kotlin/tree/master/libraries/examples/kotlin-jsr223-local-example

Nat*_*nPB 1

我刚刚通过添加来修复

compile 'org.jetbrains.kotlin:kotlin-compiler:1.3.11'
compile 'org.jetbrains.kotlin:kotlin-script-runtime:1.3.11'
compile 'org.jetbrains.kotlin:kotlin-script-util:1.3.11'
compile 'org.jetbrains.kotlin:kotlin-compiler-embeddable:1.3.11'
Run Code Online (Sandbox Code Playgroud)

给我的build.gradle

PS: 1.3.11 是我的 Kotlin 版本。