Gradle uses whatever JDK it finds in the PATH or JAVA_HOME. So if you remove sourceCompatibility and targetCompatibility it should build the project with the Java version used on the machine where the project runs. Of course, this does mean that you shouldn't have constructs like lambdas in the code or compilation on Java 7 will fail.
You should also be aware that starting with Gradle 5 support for Java 7 will be dropped and it will run only with Java 8 (or newer).
Another way to do it is to specify the JDK at runtime, see this link
If you want to build for multiple Java versions at the same time, you can use something like this:
task compile7(type: JavaCompile) {
source = fileTree(dir: 'src', include: '**/*.java')
classpath = sourceSets.main.compileClasspath
sourceCompatibility = 1.7
targetCompatibility = 1.7
destinationDir = file('build/java7')
}
task jar7(type: Jar, dependsOn: compile7) {
from('build/java7')
archiveName = 'project-JDK7.jar'
destinationDir = file('build/jars')
}
task compile8(type: JavaCompile) {
source = fileTree(dir: 'src', include: '**/*.java')
classpath = sourceSets.main.compileClasspath
sourceCompatibility = 1.8
targetCompatibility = 1.8
destinationDir = file('build/java8')
}
task jar8(type: Jar, dependsOn: compile8) {
from('build/java8')
archiveName = 'project-JDK8.jar'
destinationDir = file('build/jars')
}
You can call gradle jar7 jar8
to build jars for both java versions you want. Of course, the code above can be improved to parametrize the operations, like this:
ext.javaVer = project.hasProperty('javaVer') ? project.getProperty('javaVer') : '1.7'
task compileJ(type: JavaCompile) {
source = fileTree(dir: 'src', include: '**/*.java')
classpath = sourceSets.main.compileClasspath
sourceCompatibility = javaVer
targetCompatibility = javaVer
destinationDir = file('build/' + javaVer)
}
task jarJ(type: Jar, dependsOn: compileJ) {
from('build/' + javaVer)
archiveName = 'project-' + javaVer + '.jar'
destinationDir = file('build/jars')
}
Using this format you would call gradle jarJ -P javaVer=1.8
and gradle jarJ
to build for Java 8 and Java 7.