代码之家  ›  专栏  ›  技术社区  ›  Thufir

包装a Kotlin。JAR中用于执行的类文件

  •  0
  • Thufir  · 技术社区  · 7 年前

    在a之后 tutorial 在“Kotlin–Compile and Run from Windows Command Line”中,缺少一个清单:

    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$ 
    

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

    1 回复  |  直到 7 年前
        1
  •  3
  •   madhead    7 年前

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

    你好千吨 :

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

    kotlinc&壳 :

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