Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin program error: no main manifest attribute in jar file

Tags:

kotlin

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

like image 924
diwuu Avatar asked Dec 14 '22 11:12

diwuu


1 Answers

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 avoid the duplicate handling strategy error
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE

    // 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!
like image 180
Sylhare Avatar answered Dec 18 '22 00:12

Sylhare