简体   繁体   English

我可以使用 Java Scripting API 将 kotlin 作为脚本运行吗

[英]Can I run kotlin as script with Java Scripting API

I want to run kotlin code as script from java with Java Scripting API similar to this for javascript:我想使用与 javascript 类似的Java Scripting API将 kotlin 代码作为来自 java 的脚本运行:

import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("print('Hello, World')");
    }
}

or with similar APIs like this.或使用类似的 API。

Yes, it's possible starting from the Kotlin 1.1: http://kotlinlang.org/docs/reference/whatsnew11.html#javaxscript-support是的,可以从 Kotlin 1.1 开始: http : //kotlinlang.org/docs/reference/whatsnew11.html#javaxscript-support

KEEP-75 has an example of the JSR-223 API call: KEEP-75有一个 JSR-223 API 调用的例子:

 val engine = ScriptEngineManager().getEngineByExtension("main.kts")!! engine.eval(""" @file:DependsOn("junit:junit:4.11") org.junit.Assert.assertTrue(true) println("Hello, World!") """)

Configuration below adds Kotlin scripts engine to my Kotlin 1.2 project:下面的配置将 Kotlin 脚本引擎添加到我的 Kotlin 1.2 项目中:

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-runtime</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-util</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

Update: Starting from Kotlin 1.2.20 kotlin-script-util doesn't depend on kotlin-compiler explicitly (see https://youtrack.jetbrains.com/issue/KT-17561 ).更新:从 Kotlin 1.2.20 开始kotlin-script-util不明确依赖kotlin-compiler (参见https://youtrack.jetbrains.com/issue/KT-17561 )。 So one more module should be provided (as of the build file in example project ):所以应该再提供一个模块( 从示例项目中的构建文件开始):

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-compiler-embeddable</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

Kotlin support for the Java Scripting API is planned , but as of version 1.0.3 is not available yet. Kotlin 对 Java Scripting API 的支持是计划中的,但从 1.0.3 版本开始尚不可用。 For the mean time, you can try to use an existing open-source implementation .同时,您可以尝试使用现有的开源实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM