IntelliJ IDEA:如何在Kotlin中指定主类? [英] IntelliJ IDEA: How to specify main class in Kotlin?

查看:71
本文介绍了IntelliJ IDEA:如何在Kotlin中指定主类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用带有Kotlin Gradle项目的Intellij Idea构建一个jar.尝试配置Artifact时,Idea没有看到我的主要班级

I try to build a jar with Intellij Idea with Kotlin Gradle project. Idea doesn't see my main class when I try to configure Artifact

这是我的Gradle:

here's my Gradle :

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.60'
    id 'application'
}
group 'org.vladdrummer'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs += 'src/main/kotlin/'
}

jar {
    manifest {
        attributes 'Main-Class': 'MovieQuizBackendKt'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    compile "com.sparkjava:spark-kotlin:1.0.0-alpha"
    implementation 'com.google.code.gson:gson:2.8.2'
    runtime 'mysql:mysql-connector-java:5.1.34'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

这里的结构:

这是主要班级:

class MovieQuizBackend {

    fun main(args: Array<String>) {
        Server()
    }
}

推荐答案

在Kotlin语言中,入口点不是类内部的方法(名称后缀为 Kt 的类是从一份文件).请参阅文档.

In Kotlin language entry point is not a method inside the class (a class with the Kt suffix in the name is generated automatically from a file). See the documentation.

您需要将 MovieQuizBackend.kt 文件中的代码更改为以下内容:

Your code inside the MovieQuizBackend.kt file needs to be changed to the following:

fun main(args : Array<String>) {
    Server()
}

只需最后删除类MovieQuizBackend {} .

如果您不打算传递任何参数,甚至可以省略 args :

You can even omit args if you don't plan to pass any:

fun main() {
    Server()
}

另一种选择是在 companion对象内使用 @JvmStatic 批注:

Another option is to use @JvmStatic annotation inside the companion object:

class MovieQuizBackend {
    companion object {
        @JvmStatic fun main(args : Array<String>) {
            Server()
        }
    }
}

请注意,这样,主类仅命名为 MovieQuizBackend ,而不是 MovieQuizBackendKt ,因此您需要在 build.gradle 中进行更改:

Note that this way the main class is named just MovieQuizBackend instead of MovieQuizBackendKt, so you will need to change it in build.gradle:

jar {
    manifest {
        attributes 'Main-Class': 'MovieQuizBackend'
    }
}

这篇关于IntelliJ IDEA:如何在Kotlin中指定主类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆