Kotlin 脚本引擎抛出"unresolved reference",即使包和类是有效的



使用 Kotlin 的脚本引擎时,尝试导入包或使用任何类会抛出"未解析的引用">

javax.script.ScriptException: error: unresolved reference: mrpowergamerbr
fun loritta(context: com.mrpowergamerbr.loritta.commands.CommandContext) {
^

在 IntelliJ IDEA 中运行类时不会发生这种情况,但在生产环境中运行类时确实会发生。

虽然此 YouTrack 问题与胖 JAR 有关,但如果您不使用胖 JAR(通过启动类路径选项或类路径清单选项加载所有库(,也会发生这种情况。

要解决此问题,或者您可以像这样对启动脚本的所有依赖项:

-Dkotlin.script.classpath=jar1:jar2:jar3:jar4

例:

java -Dkotlin.script.classpath=libs/dependency1.jar:libs/dependency2.jar:yourjar.jar -jar yourjar.jar

或者,如果您愿意,可以使用类路径清单选项通过代码设置属性。

val path = this::class.java.protectionDomain.codeSource.location.path
val jar = JarFile(path)
val mf = jar.manifest
val mattr = mf.mainAttributes
// Yes, you SHOULD USE Attributes.Name.CLASS_PATH! Don't try using "Class-Path", it won't work!
val manifestClassPath = mattr[Attributes.Name.CLASS_PATH] as String
// The format within the Class-Path attribute is different than the one expected by the property, so let's fix it!
// By the way, don't forget to append your original JAR at the end of the string!
val propClassPath = manifestClassPath.replace(" ", ":") + ":Loritta-0.0.1-SNAPSHOT.jar"
// Now we set it to our own classpath
System.setProperty("kotlin.script.classpath", propClassPath)

虽然我还没有对此进行测试,但在另一个不相关的答案中,如果您自己初始化 KotlinJsr223JvmLocalScriptEngine 对象,您似乎也可以提供自己的类路径(如此处所示(

相关内容

最新更新