Home > Enterprise >  How to create executable jar in Kotlin using maven-assembly-plugin without a main class?
How to create executable jar in Kotlin using maven-assembly-plugin without a main class?

Time:11-12

I want to create an executable jar of my Kotlin codebase using the maven-assembly-plugin. In Kotlin, the main class does not have to be part of a class necessarily but the plugin wants to hear a class.

If I do create a main class, then there is no problem. Let's say I have a main class:

MyApplication.kt

package com.my.application

class MyApplication {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            .. do stuff here ..
        }
    }
}

I also configured the plugin:

pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>
                            com.my.application.MyApplication
                        </mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>

The above works. I can execute the jar successfully. However, there is no need in Kotlin to necessarily have the class with the companion object and then the annotation. I could just type:

MyApplication.kt

import com.my.application

fun main(args: Array<String>) {
    .. do stuff here ..
}

But if I then execute the jar I get an exception:

Error: Could not find or load main class com.my.application.MyApplication
Caused by: java.lang.ClassNotFoundException: com.my.application.MyApplication

How can I make this work?

CodePudding user response:

Kotlin will implicitly compile to a class which is derived from the filename suffixed with Kt. In your case it results to com.my.application.MyApplicationKt

https://kotlinlang.org/docs/java-to-kotlin-interop.html#package-level-functions

  • Related