My question: How do I set a module path for gradle build
?
I\'ve become comfortable working with Java modules from the command line. I do a frequent exe
Since Gradle 6.4 you can used set the inferModulePath property on the project Java plugin to automatically set the module path:
subprojects {
plugins.withType(JavaPlugin).configureEach {
java {
modularity.inferModulePath = true
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
}
First please note: I am on Gradle 6.6.1 with Java 15.
This is what I have observed:
in order to make the compile work, every project needs:
java {
modularity.inferModulePath = true
}
this can be turned on at root build.gradle
via
subprojects {
apply plugin: "java"
java {
modularity.inferModulePath = true
}
}
in order to use modulepath with gradle run
(ServiceLoader working WITHOUT META-INF, reflection restrictions ...) you have to use following application section:
application {
mainModule = 'org.gradle.sample.app' // name defined in module-info.java
mainClass = 'org.gradle.sample.Main'
// DO NOT USE mainClassName = 'org.gradle.sample.Main'
}
Took me quite some time to put all together from several Gradle pages --- but it is all here.
Note:
This will not but non-modular jars to the module-path.
I know it can be confusing, but it can definitely be done by gradle. You will need to use a multiproject build to have this work. In your top-most build.gradle
, do this:
subprojects {
apply plugin: 'java'
sourceCompatibility = 1.9
compileJava {
doFirst {
options.compilerArgs += [
'--module-path', classpath.asPath
]
classpath = files()
}
}
}
In your settings.gradle
:
rootProject.name = 'module-testing'
include 'src:greetMod'
include 'src:appMod'
Everything inside appMod
should be moved into a folder called appModSrc
. Do the same for greetMod
so use greetModSrc
.
Directory structure:
├── build.gradle
└── greetModSrc
├── greetPack
│ └── Hello.java
└── module-info.java
sourceSets {
main {
java {
srcDirs 'greetModSrc'
}
}
}
Directory structure:
├── appModSrc
│ ├── appPack
│ │ └── Entry.java
│ └── module-info.java
└── build.gradle
plugins {
id 'application'
}
sourceSets {
main {
java {
srcDirs 'appModSrc'
}
}
}
application {
mainClassName 'appPack.Entry'
}
jar {
doFirst {
manifest {
attributes('ModuleMainClass': mainClassName)
}
}
}
dependencies {
implementation project(':src:greetMod')
}
With this setup, you can simply run ./gradlew :src:appMod:run
:
> Task :src:appMod:run
Greetings from Hello class!
You can download the idea project here: https://github.com/smac89/multi-java9-gradle