如何将Gradle项目中Kotlin的字节码版本设置为Java 8?

2024-04-19

在 Kotlin 项目中,什么是正确的 Gradle 脚本来确保我的类将被编译为字节码版本 52 (Java 8)?

由于某种原因,即使我设置了源和目标兼容性,我的类也被编译为版本 50 (Java 6)。至少这是当我从目录打开文件时 Idea 向我展示的内容build/classes/...构建项目后。

我当前的设置如下所示。

buildscript {
    ext {
        kotlinVersion = '1.0.5-2'
        springBootVersion = '1.4.2.RELEASE'
    }
    repositories { mavenCentral() }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'

tasks.withType(JavaCompile) {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

// I also tried this and it hasn't helped
//sourceCompatibility = 1.8
//targetCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}")
    compile('org.springframework.cloud:spring-cloud-starter-stream-rabbit')
}

dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR2" } }

正如 Mark 在 Debop 的回答中指出的那样,你必须配置两者compileKotlin and compileTestKotlin。您可以这样做而无需重复:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
  kotlinOptions {
    jvmTarget = "1.8"
  }
}

对于纯 Kotlin 项目,我不认为有这些选择sourceCompatibility and targetCompatibility做任何事情,这样你就可以删除它们。

Ref: https://kotlinlang.org/docs/reference/using-gradle.html#compiler-options https://kotlinlang.org/docs/reference/using-gradle.html#compiler-options

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将Gradle项目中Kotlin的字节码版本设置为Java 8? 的相关文章

随机推荐