将Kotlin .class文件打包到JAR中执行

在关于“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) { 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属性作为执行的入口点 :

 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文件?

问题,就像在你的其他问题一样,你正在使用实例方法的类。 这根本行不通,因为main必须是静态的(而你的不是)。 在Kotlin中,你不需要一个类来定义main方法,只需要使用函数:

Hello.kt

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

kotlinc&shell

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