How to enable Java 12 preview features with Gradle?

Murali Krishna picture Murali Krishna · Mar 30, 2019 · Viewed 8.3k times · Source

When I tried to build my Java code which has switch expressions using Gradle, it throws this error:

error: switch expressions are a preview feature and are disabled by default.

I tried running ./gradlew build --enable-preview which didn't work either.

I'm using Gradle 5.3.1.

Answer

JB Nizet picture JB Nizet · Mar 30, 2019

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'])
}