Gradle tooling api fails with illegal argument exception "invalid flag: --release"

I am using gradle tooling api 6.6.1 with java 14 to build a project (To test, I’ve used spotbugs).

Here is how I’m using the project connection (this is kotlin code btw):

projectConnection
            .newBuild()
            .forTasks("spotbus-annotations:build")
            .setStandardError(stderr)
            .setStandardOutput(stdout)
            .withArguments("-S", "-d")
            .addProgressListener { event: org.gradle.tooling.events.ProgressEvent ->
                logger.info { "[${event.eventTime}] ${event.displayName}: ${event.descriptor.displayName}" }

            }
            .run()

The progress listener shows that one task had failed. However, it didn’t show muc more:

[1600928363746] Compile Java for :spotbugs-annotations:compileJava failed: Compile Java for :spotbugs-annotations:compileJava

the original exception I got was this:

org.gradle.tooling.BuildException: Could not execute build using connection to Gradle distribution 'https://services.gradle.org/distributions/gradle-6.6.1-all.zip'.

If I dig deeper, I find the actual cause:

java.lang.IllegalArgumentException: invalid flag: --release

my javac and java versions are 14, and I am able to run the build without any issues with gradlew… How did that --release option get there? is there a way to remove it?

So I’ve solved it. This issue occurs when the target java version as specified by intellij is different from the the java version used by default in the os.

In my case, the default java version I was using was java 14. However, in intellij and my project’s gradle, I had set the target api version as 8. Intellij settings and my os settings conflicted, resulting in this issue.

To fix this, either change the settings in the following places in intellij:

File | Project Structure | Platform Settings | SDKs

make sure to set the platform sdk to the same one as the OS version.

Also make sure to set the target java version in the build.gradle for your project appropriately if you need to.

Or:

if you are on Ubuntu like me:

sudo update-alternatives --config java
sudo update-alternatives --config javac

select the option that matches with the sdk defined in your build settings.

I hope this helps others who have had similar issues!