14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Gradle + Kotlin-DSLでjarを生成

Last updated at Posted at 2019-10-05

[2021/12/11 追記]

最近だとGradle Shadowを使ってjarを生成するのが楽そう.

build.gradle.kts
plugins {
  id("com.github.johnrengelman.shadow") version "6.0.0" // 使っているGradleのバージョンを指定する
}

...

dependencies {
  // implementation で指定しても大丈夫
  implementation(platform("org.jetbrains.kotlin:kotlin-bom"))

  ...
}

application {
  // Define the main class for the application.
  mainClassName = "package.MainKt"
}

val jar by tasks.getting(Jar::class) {
  manifest {
     attributes["Main-Class"] = "package.MainKt"
  }
}

あとは

./gradlew shadowJar

を実行するだけ

追記終わり.以下本文


Kotlin-DSLでGradleを使っているのだが,実行可能jarを生成する方法が意外と見つからなかったので備忘録的に書き留めておく.

build.gradle.kts
plugins {
    application
}

dependencies {
    // 依存ライブラリをjarに固めるためには'compile'で記述する必要がある

    // Use the Kotlin JDK 8 standard library.
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    // Use the Kotlin test library.
    testCompile("org.jetbrains.kotlin:kotlin-test")

    // Use the Kotlin JUnit integration.
    testCompile("org.jetbrains.kotlin:kotlin-test-junit")
}

application {
    // Define the main class for the application
    mainClassName = "com.example.MainKt"
}

// 'gradle jar'を使えるようにタスクを定義
val jar by tasks.getting(Jar::class) {
    manifest {
        attributes["Main-Class"] = "com.example.MainKt"
    }

    from(
            configurations.compile.get().map {
                if (it.isDirectory) it else zipTree(it)
            }
    )
    exclude("META-INF/*.RSA", "META-INF/*.SF", "META-INF/*.DSA")
}

groovyの記事はいっぱい見つかるんだけどね...

[11/4追記]
この記事の目的とは逸れるが,./gradlew run実行時に実行時引数を与える方法も一応書いておく

build.gradle.kts
import kotlin.text.Regex

val run by tasks.getting(JavaExec::class) {
    if (project.hasProperty("args")) {
        args = (project.property("args") as String).split(Regex("\\s+))
    }
}

実行時は

./gradlew run -Pargs="hoge fuga piyo ..."

引数に補完が効かないことに注意

14
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?