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

亡梦爱人 提交于 2019-12-01 11:09:00

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 👍
  • I verified that module-info.class is in JDK 9 format (8th byte is 0x35v.53), while other classes are in JDK 8 format (8th byte is 0x34v.52) 👍
  • however, disabling org.javamodularity.moduleplugin is unsatisfactory, because it means that tests will no longer run on module path, etc. 👎
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!