Gradle Goodness: Enabling Preview Features For Java
Check out how to enable and play with preview Java features in Gradle.
Join the DZone community and get the full member experience.
Join For FreeJava introduced preview features in the language starting in Java 12. These features can be tried out by developers, but are still subject to change and can even be removed in the next release. By default, the preview features are not enabled when we want to compile and run our Java code. We must explicitly specify that we want to use the preview feature to the Java compiler and Java runtime using the command-line argument --enable-preview
. In Gradle, we can customize our build file to enable preview features. We must customize tasks of type JavaCompile
and pass --enable-preview
to the compiler arguments. Also tasks of type Test
and JavaExec
must be customized where we need to add the JVM argument --enable-preview
.
In the following Gradle build script written in Kotlin, we have a Java project written with Java 15 where we reconfigure the tasks to enable preview features:
xxxxxxxxxx
plugins {
java
application
}
repositories {
mavenCentral()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.1")
}
application {
mainClass.set("mrhaki.Patterns")
}
tasks {
val ENABLE_PREVIEW = "--enable-preview"
// In our project we have the tasks compileJava and
// compileTestJava that need to have the
// --enable-preview compiler arguments.
withType<JavaCompile>() {
options.compilerArgs.add(ENABLE_PREVIEW)
// Optionally we can show which preview feature we use.
options.compilerArgs.add("-Xlint:preview")
// Explicitly setting compiler option --release
// is needed when we wouldn't set the
// sourceCompatiblity and targetCompatibility
// properties of the Java plugin extension.
options.release.set(15)
}
// Test tasks need to have the JVM argument --enable-preview.
withType<Test>() {
useJUnitPlatform()
jvmArgs.add(ENABLE_PREVIEW)
}
// JavaExec tasks need to have the JVM argument --enable-preview.
withType<JavaExec>() {
jvmArgs.add(ENABLE_PREVIEW)
}
}
Written with Gradle 6.8.3
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments