Task: load the classes of an application consisting of two modules (the modules are linked via module-info.java
) using a custom class loader (CustomClassLoader
).
Modules (declared via module-info.java
):
manual.fewmodules.together.dependent
:Main
- a class containing amain
method creating an instance of theCat
class and calling theCat::talk
method;CustomClassLoader
- a class that is an implementation of a custom class loader;
manual.fewmodules.together.dependency
:Cat
- loadable class with thetalk
method, which prints the string "Meow" tostdout
.
To change the system loader to a custom CustomClassLoader
in documentation of the ClassLoader.getSystemClassLoader()
method it is written that for this it is necessary for the JVM to pass the name of the new system class loader through the argument java.system.class.loader
, and also to define a public constructor with a parameter of type ClassLoader
, which will be passed as AppClassLoader
when created.
Using modulepath
:
java17 -Djava.system.class.loader=ru.ispras.j17.auto.fewmodules.together.dependent.CustomClassLoader \
-p dependent-1.0.jar:dependency-1.0.jar -m auto.fewmodules.together.dependent
Output:
Main Class Module is module auto.fewmodules.together.dependent
Cat Class Module is module auto.fewmodules.together.dependency
System ClassLoader is ru.ispras.j17.auto.fewmodules.together.dependent.CustomClassLoader@5a07e868
Main Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@42a57993
Cat Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@42a57993
Meow
- Regarding Java 17. Auto Loading (Java 17 style) the only difference is that there are two
modules that
are
loaded using
AppClassLoader
.
Same as in Java 17. Auto Loading (Java 17 style).
- In
module-info.java
of thedependency
module you need to export the package with theCat
class, and inmodule-info.java
of thedependent
module, specify the dependency on thedependency
module and export the custom class loaderCustomClassLoader
:
// dependency/src/module-info.java
module auto.fewmodules.together.dependency {
exports ru.ispras.j17.auto.fewmodules.together.dependency;
}
// dependent/src/module-info.java
module.auto.fewmodules.together.dependent {
requires auto.fewmodules.together.dependency:
exports ru.ispras.j17.auto.fewmodules.together.dependent to java.base;
}