kotlin program error: no main manifest attribute in jar file

后端 未结 2 2000
旧时难觅i
旧时难觅i 2020-12-04 02:38

I wrote a simple kotlin helloworld program hello.kt

fun main(args: Array) {
    println("Hello,          


        
相关标签:
2条回答
  • 2020-12-04 03:20

    Try to upgrade to version 1.3.41 and using JDK 1.11+.

    0 讨论(0)
  • 2020-12-04 03:22

    I came accross this answer while having the same issue with Kotlin and gradle. I wanted to package to get the jar to work but kept on pilling errors.

    With a file like com.example.helloworld.kt containing your code:

    fun main(args: Array<String>) {
        println("Hello, World!")
    }
    

    So here is what the file build.gradle.kts would look like to get you started with gradle.

    import org.gradle.kotlin.dsl.*
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    plugins {
      application
      kotlin("jvm") version "1.3.50"
    }
    
    // Notice the "Kt" in the end, meaning the main is not in the class
    application.mainClassName = "com.example.MainKt"
    
    dependencies {
      compile(kotlin("stdlib-jdk8"))
    }
    
    tasks.withType<KotlinCompile> {
      kotlinOptions.jvmTarget = "1.8"
    }
    
    tasks.withType<Jar> {
        // Otherwise you'll get a "No main manifest attribute" error
        manifest {
            attributes["Main-Class"] = "com.example.MainKt"
        }
    
        // To add all of the dependencies otherwise a "NoClassDefFoundError" error
        from(sourceSets.main.get().output)
    
        dependsOn(configurations.runtimeClasspath)
        from({
            configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
        })
    }
    

    So once you gradle clean build you can either do:

    gradle run
    > Hello, World!
    

    Assuming your projector using the jar in build/libs/hello.jar assuming that in your settings.gradle.kts you have set rootProject.name = "hello"

    Then you can run:

    java -jar hello.jar
    > Hello, World!
    
    0 讨论(0)
提交回复
热议问题