Dark theme | Light theme

November 9, 2010

Gradle Goodness: Set Java Version Compatibility

We can use the properties sourceCompatibility and targetCompatibility provided by the Java plugin to define the Java version compatibility for compiling sources. The value of these properties is a JavaVersion enum constant, a String value or a Number. If the value is a String or Number we can even leave out the 1. portion for Java 1.5 and 1.6. So we can just use 5 or '6' for example.

We can even use our own custom classes as long as we override the toString() method and return a String value that is valid as a Java version.

apply plugin: 'java'

sourceCompatibility = 1.6 // or '1.6', '6', 6, JavaVersion.VERSION_1_6, new Compatibility('Java 6')

class Compatibility {
    String version

    Compatibility(String versionValue) {
        def matcher = (versionValue =~ /Java (\d)/)
        version = matcher[0][1]

    String toString() { version }

Written with Gradle 0.9.