├── .dockerignore ├── .gitignore ├── .travis.yml ├── Dockerfile ├── README.adoc ├── UNLICENSE.txt ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── hello1 ├── build.gradle └── src │ └── main │ └── java │ ├── com │ └── greetings │ │ └── Main.java │ └── module-info.java ├── hello2 ├── build.gradle └── src │ └── main │ └── java │ ├── com │ ├── greetings │ │ └── Main.java │ └── hidden │ │ └── HiddenBaseClass.java │ └── module-info.java ├── settings.gradle ├── shared ├── build.gradle └── src │ └── main │ └── java │ ├── com │ ├── hidden │ │ └── HiddenBaseClass.java │ └── shared │ │ ├── DerivedClass.java │ │ └── StringSupplier.java │ └── module-info.java ├── src └── main │ └── java │ ├── com │ └── app │ │ └── Main.java │ └── module-info.java └── step.sh /.dockerignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | *.iml 4 | build 5 | out 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | services: 4 | - docker 5 | 6 | before_install: 7 | - docker pull openjdk:11-slim 8 | 9 | script: 10 | - docker build -t java-9-no-jar-hell . 11 | - docker run -it --rm java-9-no-jar-hell 12 | 13 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:11-slim 2 | MAINTAINER Torsten Werner 3 | 4 | WORKDIR /usr/src/app 5 | 6 | # download the gradle wrapper 7 | COPY gradlew /usr/src/app/ 8 | COPY gradle /usr/src/app/gradle/ 9 | RUN ./gradlew --version 10 | 11 | # build the project and run tests 12 | COPY . /usr/src/app/ 13 | RUN ./gradlew build 14 | 15 | CMD ["./gradlew", "run"] 16 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Avoid the JAR hell with Java >= 9 Jigsaw 2 | 3 | * Make sure that JAVA_HOME points to a version 11 jdk. 4 | ** On OS X: 5 | 6 | export JAVA_HOME=$(/usr/libexec/java_home 11) 7 | 8 | * Build everything and run the app with 9 | 10 | ./gradlew run 11 | 12 | * The output will show that 2 versions of the same module have been loaded at the same time: 13 | 14 | Greetings from version ONE! 15 | Greetings from version TWO! 16 | 17 | * You can see the output at travis-ci: https://travis-ci.org/torstenwerner/java-9-no-jar-hell 18 | 19 | == Some background 20 | 21 | The directories hello1 and hello2 contain almost the same code with just some small modification in the run() method. It 22 | simulates loading 2 different versions of the same module. It would be impossible to use both JARs in the same 23 | classpath. But it is possible to work around that limitation by constructing 2 ModuleLayer instances. That is what main code in 24 | link:src/main/java/com/app/Main.java[Main.java] is doing. 25 | 26 | More information about Java 9 Jigsaw module system: http://openjdk.java.net/projects/jigsaw/ 27 | 28 | I have tested it with gradle 5.0. 29 | 30 | == Continuous Integration thanks to Travis CI 31 | 32 | Build image:https://api.travis-ci.org/torstenwerner/java-9-no-jar-hell.svg[status] 33 | at link:https://travis-ci.org/torstenwerner/java-9-no-jar-hell[Travis CI] 34 | 35 | == Docker build 36 | 37 | Instructions (use sudo on Linux): 38 | 39 | docker pull openjdk:11-slim 40 | docker build -t java-9-no-jar-hell . 41 | docker run -it --rm java-9-no-jar-hell 42 | 43 | == IntelliJ bug 44 | 45 | Switch to JDK 8 if the initial import of the gradle project fails. 46 | Switch to JDK 9 after the initial import. 47 | -------------------------------------------------------------------------------- /UNLICENSE.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | jar { 6 | baseName 'com.app' 7 | } 8 | 9 | dependencies { 10 | compile project(':shared') 11 | } 12 | 13 | def sharedModulePath = "${project(':shared').buildDir}/libs" 14 | 15 | compileJava.options.compilerArgs << '--module-path' << sharedModulePath 16 | 17 | task run(type: Exec) { 18 | dependsOn ':hello1:jar', ':hello2:jar', ':jar' 19 | commandLine 'java', '--module-path', "$buildDir/libs" + File.pathSeparator + "$sharedModulePath", '-m', 'com.app/com.app.Main', 20 | 'hello1/build/libs/', 'hello2/build/libs/' 21 | } 22 | 23 | wrapper { 24 | gradleVersion '5.0' 25 | distributionType Wrapper.DistributionType.ALL 26 | } 27 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/torstenwerner/java-9-no-jar-hell/2ccbdcc19846883af13ae027476f670a274333dd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /hello1/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | jar { 6 | baseName 'com.greetings' 7 | } 8 | 9 | dependencies { 10 | compile project(':shared') 11 | } 12 | 13 | def sharedModulePath = "${project(':shared').buildDir}/libs" 14 | 15 | compileJava.options.compilerArgs.addAll(['--module-path', sharedModulePath]) 16 | 17 | // Run the code without Layers for testing purposes. 18 | task simpleRun(type: Exec) { 19 | dependsOn 'jar' 20 | commandLine 'java', '--module-path', "$buildDir/libs:$sharedModulePath", '-m', 'com.greetings/com.greetings.Main' 21 | } 22 | -------------------------------------------------------------------------------- /hello1/src/main/java/com/greetings/Main.java: -------------------------------------------------------------------------------- 1 | package com.greetings; 2 | 3 | import com.shared.StringSupplier; 4 | 5 | public class Main implements StringSupplier { 6 | @Override 7 | public String get() { 8 | return "Greetings from version ONE!"; 9 | } 10 | 11 | /** 12 | * The main function is provided here only for testing this module in isolation. 13 | */ 14 | public static void main(String[] args) { 15 | System.out.println(new Main().get()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /hello1/src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module com.greetings { 2 | exports com.greetings; 3 | requires com.shared; 4 | provides com.shared.StringSupplier with com.greetings.Main; 5 | } 6 | -------------------------------------------------------------------------------- /hello2/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | jar { 6 | baseName 'com.greetings' 7 | } 8 | 9 | dependencies { 10 | compile project(':shared') 11 | } 12 | 13 | def sharedModulePath = "${project(':shared').buildDir}/libs" 14 | 15 | compileJava.options.compilerArgs.addAll(['--module-path', sharedModulePath]) 16 | 17 | // Run the code without Layers for testing purposes. 18 | task simpleRun(type: Exec) { 19 | dependsOn 'jar' 20 | commandLine 'java', '--module-path', "$buildDir/libs:$sharedModulePath", '-m', 'com.greetings/com.greetings.Main' 21 | } 22 | -------------------------------------------------------------------------------- /hello2/src/main/java/com/greetings/Main.java: -------------------------------------------------------------------------------- 1 | package com.greetings; 2 | 3 | import com.hidden.HiddenBaseClass; 4 | import com.shared.StringSupplier; 5 | 6 | public class Main extends HiddenBaseClass implements StringSupplier { 7 | @Override 8 | public String get() { 9 | return "Greetings from version TWO!"; 10 | } 11 | 12 | /** 13 | * The main function is provided here only for testing this module in isolation. 14 | */ 15 | public static void main(String[] args) { 16 | System.out.println(new Main().get()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /hello2/src/main/java/com/hidden/HiddenBaseClass.java: -------------------------------------------------------------------------------- 1 | package com.hidden; 2 | 3 | public class HiddenBaseClass { 4 | static { 5 | final Class klass = HiddenBaseClass.class; 6 | System.out.printf("Loading class %s from class loader %s with parent %s.\n", 7 | klass, klass.getClassLoader(), klass.getClassLoader().getParent()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /hello2/src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module com.greetings { 2 | exports com.greetings; 3 | requires com.shared; 4 | provides com.shared.StringSupplier with com.greetings.Main; 5 | } 6 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include 'shared', 'hello1', 'hello2' 2 | -------------------------------------------------------------------------------- /shared/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | jar { 6 | baseName 'com.shared' 7 | } 8 | -------------------------------------------------------------------------------- /shared/src/main/java/com/hidden/HiddenBaseClass.java: -------------------------------------------------------------------------------- 1 | package com.hidden; 2 | 3 | public class HiddenBaseClass { 4 | static { 5 | final Class klass = HiddenBaseClass.class; 6 | System.out.printf("Loading class %s from class loader %s with parent %s.\n", 7 | klass, klass.getClassLoader(), klass.getClassLoader().getParent()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /shared/src/main/java/com/shared/DerivedClass.java: -------------------------------------------------------------------------------- 1 | package com.shared; 2 | 3 | import com.hidden.HiddenBaseClass; 4 | 5 | public class DerivedClass extends HiddenBaseClass { 6 | } 7 | -------------------------------------------------------------------------------- /shared/src/main/java/com/shared/StringSupplier.java: -------------------------------------------------------------------------------- 1 | package com.shared; 2 | 3 | import java.util.function.Supplier; 4 | 5 | public interface StringSupplier extends Supplier { 6 | } 7 | -------------------------------------------------------------------------------- /shared/src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module com.shared { 2 | exports com.shared; 3 | } 4 | -------------------------------------------------------------------------------- /src/main/java/com/app/Main.java: -------------------------------------------------------------------------------- 1 | package com.app; 2 | 3 | import com.shared.DerivedClass; 4 | import com.shared.StringSupplier; 5 | 6 | import java.lang.module.Configuration; 7 | import java.lang.module.ModuleFinder; 8 | import java.lang.ModuleLayer; 9 | import java.nio.file.Paths; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.ServiceLoader; 13 | import java.util.Set; 14 | import java.util.stream.Collectors; 15 | import java.util.stream.StreamSupport; 16 | 17 | public class Main { 18 | private static final String MODULE_NAME = "com.greetings"; 19 | 20 | private static final DerivedClass derived = new DerivedClass(); 21 | 22 | /** 23 | * Create a new {@link java.lang.reflect.Layer} for the module com.greeting on a path. The boot layer will be the 24 | * parent of the new Layer which allows accessing modules in the boot layer from the module layer e.g. the 25 | * com.shared module. 26 | * 27 | * @param modulePath path where the module is located 28 | */ 29 | private static ModuleLayer createLayer(String modulePath) { 30 | final ModuleFinder finder = ModuleFinder.of(Paths.get(modulePath)); 31 | final ModuleLayer parent = ModuleLayer.boot(); 32 | final Configuration newCfg = 33 | parent.configuration().resolve(finder, ModuleFinder.of(), Set.of(MODULE_NAME)); 34 | return parent.defineModulesWithOneLoader(newCfg, ClassLoader.getSystemClassLoader()); 35 | } 36 | 37 | /** 38 | * Creates several layers in a batch. A new layer is created for each item in modulePaths. 39 | */ 40 | private static List createAllLayers(String[] modulePaths) { 41 | return Arrays.stream(modulePaths) 42 | .map(Main::createLayer) 43 | .collect(Collectors.toList()); 44 | } 45 | 46 | /** 47 | * Loads the services of type StringSupplier found in the layer. 48 | */ 49 | private static ServiceLoader loadServices(ModuleLayer layer) { 50 | return ServiceLoader.load(layer, StringSupplier.class); 51 | } 52 | 53 | /** 54 | * Execute all services found by the serviceLoader and print the result to stdout. It is exactly 1 service per 55 | * serviceLoader in this case. But the ServiceLoader API always works with Iterables and that is why we are using 56 | * streams here. 57 | */ 58 | private static void executeServices(ServiceLoader serviceLoader) { 59 | StreamSupport.stream(serviceLoader.spliterator(), false) 60 | .map(StringSupplier::get) 61 | .forEach(System.out::println); 62 | } 63 | 64 | /** 65 | * Load the module com.greetings multiple times from the paths specified on the command line. Create a layer for 66 | * each path. Load a service of type {@link StringSupplier} for each layer and execute each one. 67 | *

68 | * We are using {@link java.util.ServiceLoader} here because it is type safe, it is easier to use than low level 69 | * reflection, and it has been improved in Java 9. 70 | */ 71 | public static void main(String[] args) { 72 | final List layers = createAllLayers(args); 73 | // All modules are loaded now in the same jvm but in different layers. 74 | 75 | // Loading and executing the services from conflicting module versions now. 76 | layers.stream() 77 | .map(Main::loadServices) 78 | .forEach(Main::executeServices); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module com.app { 2 | // requires com.greetings; 3 | requires com.shared; 4 | uses com.shared.StringSupplier; 5 | } 6 | -------------------------------------------------------------------------------- /step.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set +x 4 | cat << task 5 | 6 | Compile 7 | 8 | task 9 | (rm -rf bin && mkdir bin) || exit 10 | mkdir bin/com.greetings 11 | set -x 12 | 13 | javac -d bin/com.greetings \ 14 | $(find src/com.greetings -name '*.java') || exit 15 | 16 | find bin -type f 17 | 18 | 19 | set +x 20 | cat << task 21 | 22 | Assemble 23 | 24 | task 25 | (rm -rf lib && mkdir lib) || exit 26 | set -x 27 | 28 | jar --create --file lib/com.greetings.jar \ 29 | --main-class=com.greetings.Main \ 30 | -C bin/com.greetings . || exit 31 | 32 | jar --print-module-descriptor --file lib/com.greetings.jar || exit 33 | 34 | 35 | set +x 36 | cat << task 37 | 38 | Run 39 | 40 | task 41 | set -x 42 | 43 | java \ 44 | -modulepath lib \ 45 | -m com.greetings 46 | --------------------------------------------------------------------------------