proper way to run kotlin application from gradle t

2020-07-01 11:04发布

问题:

I've got simple script

package com.lapots.game.journey.ims.example


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

And here is gradle task

task runExample(type: JavaExec) {
    main ='com.lapots.game.journey.ims.example.Example'
    classpath = sourceSets.main.runtimeClasspath
}

But when I try to run task gradle runExample I get error

Error: Could not find or load main class com.lapots.game.journey.ims.example.Example

What is the proper way to run application?

回答1:

Thanks to the link how to run compiled class file in Kotlin? provided by @JaysonMinard that main

@file:JvmName("Example")

package com.lapots.game.journey.ims.example


fun main(args: Array<String>) {
    print("executable!")
}

and that task

task runExample(type: JavaExec) {
    main = 'com.lapots.game.journey.ims.example.Example'
    classpath = sourceSets.main.runtimeClasspath
}

did the trick



回答2:

You can also use gradle application plugin for this.

// example.kt
package com.lapots.game.journey.ims.example

fun main(args: Array<String>) {
    print("executable!")
}

add this to your build.gradle

// build.gradle
apply plugin "application"
mainClassName = 'com.lapots.game.journey.ims.example.ExampleKt'

Then run your application as follows.

./gradlew run


回答3:

In case you're using a Kotlin buildfile build.gradle.kts you would need to do

apply {
    plugin("kotlin")
    plugin("application")
}    

configure<ApplicationPluginConvention> {
    mainClassName = "my.cool.App"
}

If you apply the application plugin using the plugins {} block instead you could make it simpler:

plugins {
    application
}

application {
    mainClassName = "my.cool.App"
}

For details see https://github.com/gradle/kotlin-dsl/blob/master/doc/getting-started/Configuring-Plugins.md



回答4:

I found another way from the @lapots answer.

In your example.kt:

@file:JvmName("Example")

package your.organization.example

fun main(string: Array<String>) {
    println("Yay! I'm running!")
}

Then in your build.gradle.kts:

plugins {
    kotlin("jvm") version "1.3.72"
    application
}

application {
    mainClassName = "your.organization.example.Example"
}


回答5:

For build.gradle.kts users

main file:

package com.foo.game.journey.ims.example


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

build.gradle.kts file:

plugins {
    application
    kotlin("jvm") version "1.3.72" // <-- your kotlin version here
}

application {
    mainClassName = "com.lapots.game.journey.ims.example.ExampleKt"
}

...

And run with the following command:

./gradlew run


标签: gradle kotlin