Compiling a project with different java source compatibility

怎甘沉沦 提交于 2019-12-21 01:59:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18190614/compiling-a-project-with-different-java-source-compatibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!