在JAR中打包Kotlin .class文件以供执行

时间:2017-10-27 15:38:44

标签: jar jvm runtime-error kotlin command-line-interface

跟随tutorial开始" Kotlin - 从Windows命令行编译和运行"那里有一个缺失的清单:

thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ ll
total 32
drwxr-xr-x  2 thufir thufir  4096 Oct 27 08:29 ./
drwx------ 46 thufir thufir 16384 Oct 27 08:03 ../
-rw-r--r--  1 thufir thufir   107 Oct 27 08:29 HelloWorld.kt
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.intellij.util.text.StringFactory to constructor java.lang.String(char[],boolean)
WARNING: Please consider reporting this to the maintainers of com.intellij.util.text.StringFactory
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ java -jar HelloWorld.jar
no main manifest attribute, in HelloWorld.jar
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ cat HelloWorld.kt 
class HelloWorld {

    fun main(args: Array<String>) {
        println("Hello, world!" + args[0])
    }
}
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ kotlin -classpath HelloWorld.jar HelloWorldKt
error: could not find or load main class HelloWorldKt
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ kotlin -classpath HelloWorld.jar HelloWorld
error: 'main' method of class HelloWorld is not static. Please ensure that 'main' is either a top level Kotlin function, a member function annotated with @JvmStatic, or a static Java method
thufir@dur:~/kotlin$ 

果然,jar缺少Main-Class属性作为entry point执行:

thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ jar -xf HelloWorld.jar 
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ tree META-INF/
META-INF/
└── MANIFEST.MF

0 directories, 1 file
thufir@dur:~/kotlin$ 
thufir@dur:~/kotlin$ cat META-INF/MANIFEST.MF 
Manifest-Version: 1.0
Created-By: JetBrains Kotlin

thufir@dur:~/kotlin$ 

为什么教程能够运行他们创建的jar文件?

1 个答案:

答案 0 :(得分:2)

与其他问题一样,问题在于您使用的是带有实例方法的类。它根本不起作用,因为main必须是静态的(而你的不是)。在Kotlin中,您不需要一个类来定义main方法,只需使用函数:

Hello.kt

fun main(args: Array<String>) {
    println("Hello, world!" + args[0])
}

kotlinc&amp;外壳

$ kotlinc Hello.kt -include-runtime -d HelloWorld.jar
$ java -jar HelloWorld.jar test
Hello, world!test