Compile a JDK 8 project + a JDK 9 “module-info.java” in Gradle

前端 未结 1 1501
小蘑菇
小蘑菇 2021-01-05 22:43

I\'m working on a Java library targeting JDK 8, and I\'m building it in Gradle 5 using OpenJDK 11. In order to target JDK 8, I\'m javac\'s --release option.

However,

相关标签:
1条回答
  • 2021-01-05 23:34

    EDIT: This functionality is now supported by Gradle Modules Plugin since version 1.5.0.

    Here's a working build.gradle snippet:

    plugins {
        id 'java'
        id 'org.javamodularity.moduleplugin' version '1.5.0'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compileOnly 'org.projectlombok:lombok:1.18.6'
    }
    
    modularity.mixedJavaRelease 8
    

    OK, I managed to get this working by:

    1. disabling org.javamodularity.moduleplugin
    2. removing the custom source set (it wasn't necessary)
    3. adding a custom compileModuleInfoJava task and setting its --module-path to the classpath of the compileJava task (inspired by this Gradle manual)

    Here's the full source code of build.gradle:

    plugins {
        id 'java'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compileOnly 'org.projectlombok:lombok:1.18.6'
    }
    
    compileJava {
        exclude 'module-info.java'
    
        options.compilerArgs = ['--release', '8']
    }
    
    task compileModuleInfoJava(type: JavaCompile) {
        classpath = files() // empty
        source = 'src/main/java/module-info.java'
        destinationDir = compileJava.destinationDir // same dir to see classes compiled by compileJava
    
        doFirst {
            options.compilerArgs = [
                    '--release', '9',
                    '--module-path', compileJava.classpath.asPath,
            ]
        }
    }
    
    compileModuleInfoJava.dependsOn compileJava
    classes.dependsOn compileModuleInfoJava
    

    Notes:

    • it compiles
    0 讨论(0)
提交回复
热议问题