簡體   English   中英

使用Kotlin和Gradle

[英]using Kotlin with Gradle

我是KotlinGradle新手,並嘗試按照這些步驟進行操作,因此我得到了以下2個文件:

在運行gradle init我將build.gradle更改為:

// set up the kotlin-gradle plugin
buildscript {
    ext.kotlin_version = '1.1.2-2'

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

// apply the kotlin-gradle plugin
apply plugin: "kotlin"
apply plugin: 'application'

mainClassName = "hello.main"

// add kotlin-stdlib dependencies.
repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

Hello.kt

package hello   

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

然后我運行gradle build並獲得build\\classes\\main\\hello\\HelloKt.class

我的問題是:為什么生成的文件是.class而不是.jar以及如何獲取.jar文件以及如何運行它,我嘗試使用kotlin -classpath HelloKt.class main運行生成的文件但是出現錯誤error: could not find or load main class hello.main

這些類是Kotlin編譯器的直接輸出,之后應由Gradle將它們打包到JAR中。 要構建JAR,您可以像在Java項目中一樣運行jar任務:

gradle jar

由於任務依賴性,此任務通常gradle build期間運行。

.jar . 這將把Kotlin類打包成一個JAR存檔(與其他JVM類一起,如果你有一個多語言項目),通常位於build/libs/ .jar

關於運行JAR,請參閱此問答以獲取詳細說明:( 鏈接)

感謝@hotkey的答案,它幫助我走正確的道路。

首先,主類聲明中存在錯誤,因為它應遵循新的方法,即以下格式:

mainClassName = '[your_namespace].[your_arctifact]Kt'

namespace =包名稱

arctifact =文件名

所以,考慮上面例子中給出的名稱為: Hello.kt ,命名空間為hello的名稱,則:

mainClassName = `[hello].[Hello]Kt`

使用前面的方法,其中包含:

apply plugin: 'application'
mainClassName = 'hello.HelloKt'

生成的.jar文件不包含kotlin運行時,因此執行它的唯一方法是:

d:/App/build/libs/kotlin -cp App.jar hello.HelloKt

但是為了生成一個可以自行執行的自包含jar ,並且包含kotlin runtime那么build.gradle應該寫成:

// set up the kotlin-gradle plugin
buildscript {
    ext.kotlin_version = '1.1.2-2'

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

// apply the kotlin-gradle plugin
apply plugin: "kotlin"


// add kotlin-stdlib dependencies.
repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

jar {
    manifest {
        //Define mainClassName as: '[your_namespace].[your_arctifact]Kt'
        attributes 'Main-Class': 'hello.HelloKt'
    }

    // NEW LINE HERE !!!
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

然后是gradle build[your_working_folder].jar文件將在build/libs文件夾中生成,假設工作文件夾名稱是app,則將生成文件app.jar。

要運行此文件,可以使用以下兩個命令之一:

D:\App\build\libs\java -jar App.jar

要么

D:\App\build\libs\kotlin App.jar hello.HelloKt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM