Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

kotlin program error: no main manifest attribute in jar file

I wrote a simple kotlin helloworld program hello.kt

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

Then I compiled it with kotlinc

$kotlinc hello.kt -include-runtime -d hello.jar

there was no errors and hello.jar was generated. when I ran it

$java -jar hello.jar

it said there is no main manifest attribute in hello.jar

$no main manifest attribute, in hello.jar

I couldn't figure out this problem. My kotlin version is 1.3.40, JDK version is 1.8.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...