How to enable Java 12 preview features with Gradle?
Here is another version using the Gradle Kotlin DSL for usage in build.gradle.kts
:
plugins {
`java-library`
}
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_12
}
tasks.withType<JavaCompile> {
options.compilerArgs.add("--enable-preview")
}
tasks.test {
useJUnitPlatform()
jvmArgs("--enable-preview")
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.4.2")
}
You need to configure the JavaCompile
tasks, so that Gradle passes this option to the Java compiler when compiling.
Something like this should work:
tasks.withType(JavaCompile).each {
it.options.compilerArgs.add('--enable-preview')
}
To run the app/tests we need to add jvmArgs
.
Example:
test {
jvmArgs(['--enable-preview'])
}
Currently there seem not to be a single place for defining that. You should do it for all of the task types (compile, test runtime or java exec related tasks). I found myself fully covered with:
tasks.withType(JavaCompile) {
options.compilerArgs += "--enable-preview"
}
tasks.withType(Test) {
jvmArgs += "--enable-preview"
}
tasks.withType(JavaExec) {
jvmArgs += '--enable-preview'
}