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

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

出于某种原因,即使我设置了源和目标兼容性,我的类仍被编译为版本 50 (Java 6)。至少这是我在构建项目后从目录 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 的回答中指出的那样,您必须同时配置 compileKotlincompileTestKotlin。您可以通过这种方式做到不重复:

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

对于纯 Kotlin 项目,我认为选项 sourceCompatibilitytargetCompatibility 没有任何作用,因此您可以删除它们。

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

https://stackoverflow.com/questions/41113268/

相关文章:

android - build.gradle 文件中的 compileKotlin block 抛出

kotlin - Dagger 和 Kotlin 。 Dagger 不生成组件类

arrays - 字符串数组文字?我如何简单地编码?

android - IllegalArgumentException : Parameter spe

android - Kotlin Coroutines 在 Android 中的正确方式

kotlin - 为什么泛型类型属性可以为空?

kotlin - 如何在 Kotlin 中向 Java 类添加静态方法

kotlin - Kotlin 中的扩展字段

java - Android Studio 3.0 金丝雀 1 : Kotlin tests or

arrays - 如何比较 Kotlin 中的两个数组?