如何将 Gradle 项目中 Kotlin 的字节码版本设置为 Java 8? [英] How to set up Kotlin's byte code version in Gradle project to Java 8?
问题描述
在 Kotlin 项目中,什么是正确的 Gradle 脚本以确保我的类将被编译为字节码 ver 52 (Java 8)?
In Kotlin project, what is a proper Gradle script to make sure my classes will be compiled to byte code ver 52 (Java 8)?
出于某种原因,即使我设置了源和目标兼容性,我的类还是编译为 ver 50 (Java 6).至少这是我在构建项目后从目录 build/classes/...
打开文件时 Idea 向我显示的内容.
For some reason my classes are compiled as ver 50 (Java 6) even though I set up source and target compatibility. At least this is what Idea shows me when I open file from directory build/classes/...
after building the project.
我目前的设置是这样的.
My current set up looks like this.
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
和 compileTestKotlin
.你可以这样做而无需重复:
As Mark pointed out on Debop's answer, you have to configure both compileKotlin
and compileTestKotlin
. You can do it without duplication this way:
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
对于纯 Kotlin 项目,我认为选项 sourceCompatibility
和 targetCompatibility
没有任何作用,因此您可以删除它们.
For a pure Kotlin project, I don't think the options sourceCompatibility
and targetCompatibility
do anything, so you may be able to remove them.
参考:https://kotlinlang.org/docs/reference/using-gradle.html#compiler-options
这篇关于如何将 Gradle 项目中 Kotlin 的字节码版本设置为 Java 8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!