我正在尝试编写一个界面(GUI)来运行一些 Kotlin 脚本。我从一个 Junit 测试开始,以确保我可以执行脚本。我什至无法加载 kotlin 引擎。看起来我的依赖项(gradle)是有序的,但你可以仔细检查一下。
compile name: 'kotlin-script-runtime',
group: 'org.jetbrains.kotlin', version: kotlin_version
compile name: 'kotlin-script-util',
group: 'org.jetbrains.kotlin', version: kotlin_version
compile name: 'kotlin-compiler-embeddable',
group: 'org.jetbrains.kotlin', version: kotlin_version
多于:ext.kotlin_version = '1.3.0'
这是失败的测试:
@Test
fun testEngine() {
// attempt to load script engine class before looking for it
val ktsEngineClassName = "org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine";
var clazz: Class<*>? = null;
// assign the clazz variable inside a closure to catch ClassNotFound
assertDoesNotThrow({clazz = Class.forName(ktsEngineClassName)}, "could not find $ktsEngineClassName")
// just to make sure it's there
assertNotNull(clazz, "could not find $ktsEngineClassName")
// so far so good, but here's the problem:
val engineName = "kotlin"
// load the factory
val factory = ScriptEngineManager().getEngineByName(engineName)?.factory
// and test that we got it
assertNotNull(factory, "didn't find factory for '$engineName'." +
"\navailable: ${ScriptEngineManager().engineFactories}")
}
最后一次assertNotNull
失败,输出如下:
org.opentest4j.AssertionFailedError: didn't find factory for 'kotlin'.
available: [jdk.nashorn.api.scripting.NashornScriptEngineFactory@1a41b1fc] ==> expected: not <null>
可以看到,虽然脚本引擎类似乎加载Class.forName
成功,但名称kotlin
并没有注册,可用引擎列表只包含 Nashorn。如何确保引擎已注册?