Gradle’s Java 9 support explained
© Shutterstock / docstockmedia
Java SE 9 was released almost a month ago and we already have Java 9 support in Eclipse Oxygen, Spring Framework 5.0, IntelliJ IDEA and more. Now Gradle has joined the club. Let’s see what this means.
It’s been almost a month since Java SE 9 was released — even though Eclipse Oxygen, Spring Framework 5.0, Azul Systems’ Zulu and IntelliJ IDEA 2017.2 (to name a few) are already offering Java 9 support, not everyone is there yet.
Gradle recently joined the club — Eric Wendelin, Principal Engineer at Gradle wrote in a recent blog post that “as of Gradle 4.2.1, building and running Java applications using major distributions of JDK 9 such as Oracle JDK9, OpenJDK9 and Azul JDK9 is fully supported. Further, cross-compilation (built by JDK9 but runs on JDK8) is supported.”
Wendelin explained that some builds will inevitably break when upgrading to the latest Java version, no matter your weapon of choice (a.k.a. build tool). Although he acknowledged that “the Java team have made good and necessary changes to the JDK to facilitate better software architecture and security, this has meant removing access to some APIs.”
Even if your project is ready, some tools and Gradle plugins have not yet been updated to work with Java 9.
Jigsaw support in Gradle
If you don’t know how to use Java modules with Gradle, here’s a guide that might come in handy. In short, it will teach you exactly what you need to change in your Java application to:
- produce Java 9 modules for your java libraries.
- consume Java 9 modules as your dependencies.
- use Java’s
ServiceLoaderpattern with Java 9 modules.
- run an application using Java 9 modules.
- use an experimental plugin to do all of this more simply.
Even though there’s no first-class support for Java 9 modules in Gradle version 4.2 yet, if you skim through this guide you’ll find out how to experiment with them before that support is complete.
“A bottom-up approach (convert libraries with no dependencies first) is recommended if you wish to incrementally convert to Java 9 modules,” Wendelin added. “After all, modules are consumable as regular JARs. Be mindful of automatic modules when “legacy” JARs are added to the
Java Library Plugin
Gradle 3.4 introduced the Java Library Plugin which enforces strong encapsulation for libraries by separating
api dependencies (those meant to be exposed to consumers) from
implementation dependencies whose internals are not leaked to consumers, according to Wendelin. Still, this doesn’t mean that use of Java classpaths is eliminated.
For more information about the motivation and usage of the Java Library Plugin, read this post. Keep in mind that the Java Library Plugin is useful for projects that use Java 7 and above so there’s no need to migrate to Java 9 in order to have stronger encapsulation.
If you want to learn how to use Java modules with Gradle, you should read the Building Java 9 Modules guide.