简体   繁体   中英

How do I specify the required Java version in a Gradle build?

I would like to set the required Java version (eg 7 or 8) in my Gradle build file without having to specify the actual path to a local JDK installation.

Is this possible?

This feature was just added to Gradle 6.7 as Java toolchains :

// build.gradle.kts

plugins {
    id("java-library") // or id("application")
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(11))
    }
}

With this in place Gradle will automatically download & use the appropriate JDK (using AdoptOpenJDK by default) for the specified Java version.

TLDR; Thanks @franklin-yu "targetCompatibility = '1.7' -> your user can compile with 8 and run with 7."

See Gradle, "sourceCompatibility" vs "targetCompatibility"?

targetCompatibility = '1.7' does the trick for eg Java 7

Use sourceCompatibility = '1.7' for the language level

You can try this:

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

tasks.withType<JavaCompile> {
    options.compilerArgs.addAll(arrayOf("--release", "8"))
}

This will also give JDK compliance to you. You can also see the following related issues:

In the build.gradle file, add the following two lines:

sourceCompatibility = '1.8'
targetCompatibility = '1.8'

The targetCompatibility defines the generated JVM bytecode version (this is the version that users of your application need). The sourceCompatibility defines which source code constructs are allowed (eg you need Java 1.8 or higher to use lambda expressions in source code).

Source

Based on the answer of CletusW. In windows 10, it seems that the new installed Java will not be chosen automatically, so I check it manually.

apply plugin: 'java'
java.toolchain.languageVersion = JavaLanguageVersion.of(15)  // auto install



// check JDK version
if (!System.getProperty("java.home").contains(java.toolchain.languageVersion.get().toString())) {
    def msg = ('JDK in this project: ' + System.getProperty('java.home') + '\n' +
            'In this project, you should use JDK-' + java.toolchain.languageVersion.get())
    throw new GradleException(msg)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM