Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling a project with different java source compatibility

I have a multiproject configuration with 3 different projects.

2 of the projects depend on the 3rd project, which I named 'core'. Depending on the project, 'core' has to compile to a jar, with source compatibility for 1.4 and 1.6 respectively, into outputs core-1.4.jar and core-1.6.jar.

Is it possible to do this with a single build.gradle, or what would be the best way to do this? How can I specify which jar in particular in my dependencies for each of the 2 projects?

like image 772
al. Avatar asked Aug 12 '13 15:08

al.


1 Answers

The question is fundamentally about how to produce and consume two variations of an artifact that are based off the same Java code. Provided that you really need to produce two Jars that only differ in their target compatibility (which I would first question), one way to achieve this is to use the Java plugin's main source set (and the tasks that come along with it) to produce the first variation, and a new source set to produce the second variation. Additionally, the second variation needs to be published via its own configuration so that depending projects can reference it. This could look as follows:

core/build.gradle:

apply plugin: "java"

sourceCompatibility = 1.4

sourceSets {
    main1_4 {
        def main = sourceSets.main
        java.srcDirs = main.java.srcDirs
        resources.srcDirs = main.resources.srcDirs
        compileClasspath = main.compileClasspath
        runtimeClasspath = main.runtimeClasspath
    }
}

compileJava {
    targetCompatibility = 1.6
}

compileMain1_4Java {
    targetCompatibility = 1.4    
}

jar {
    archiveName = "core-1.6.jar"
}

main1_4Jar {
    archiveName = "core-1.4.jar"
}

configurations {
    archives1_4
}

artifacts {
    archives1_4 main1_4Jar
}

In depending projects:

dependencies {
    compile project(":core") // depend on 1.6 version
    compile project(path: ":core", configuration: "archives1_4") // depend on 1.4 version
}

All of this can (but doesn't have to) be done in the same build script. See the "multi-project builds" chapter in the Gradle User Guide for details.

like image 74
Peter Niederwieser Avatar answered Nov 13 '22 07:11

Peter Niederwieser