Skip to content

[Gradle & Actions] Use Java 11 for compiling and checks instead of Java 8 #10

@coderbot16

Description

@coderbot16

We can use the compilerArgs option to still make sure that our code is compatible with Java 8 even though we're compiling on Java 11:

compileJava {
    options.compilerArgs.addAll(['--release', '8')]
}

Unfortunately, that fails on Java 8 because the flag was only added in Java 9. However, this blog post has a good solution:

// If on JDK 9+, verify project cross-compiles on its 'sourceCompatible' JVM version (see https://github.com/melix/mrjar-gradle/blob/master/jdks.gradle)
if (project.hasProperty('crossCompile')) {
    if (JavaVersion.current().java9Compatible) {
        project.afterEvaluate {
            tasks.withType(JavaCompile) {
                def version = compat(sourceCompatibility)
                project.logger.info("Configuring $name to use --release $version")
                options.compilerArgs.addAll(['--release', version])
            }
        }
    } else {
        project.logger.warn("-PcrossCompile not supported prior to JDK 9; using JDK ${JavaVersion.current()}")
    }
}

// This function converts 1.8 -> 8
static String compat(String src) {
    if (src.contains('.')) {
        src.substring(src.lastIndexOf('.')+1)
    } else {
        src
    }
}

While that code supports cross compiling to any version, in reality we only care about cross compiling to Java 8 and/or compiling to Java 8 on Java 8 at the moment so we can just hardcode that part in and remove the warning when cross compiling isn't supported.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions