Task: load any application class using a custom class loader (CustomClassLoader) from another module (the modules are linked via module-info.java).
Modules (declared via module-info.java):
manual.fewmodules.together.dependent:Main- a class containing themainmethod, where an instance of theCustomClassLoaderclass is created, theCatclass is loaded using it, creating an instance of the classCatand calling theCat::talkmethod;CustomClassLoader- a class that is an implementation of a custom class loader;
manual.fewmodules.together.dependency:Cat- loadable class with thetalkmethod, which prints the string "Meow" tostdout.
Using modulepath:
java17 -p dependent-1.0.jar:dependency-1.0.jar -m manual.fewmodules.together.dependentOutput:
Main Class Module is module manual.fewmodules.together.dependent
Cat Class Module is unnamed module @23fc625e
Main Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@42a57993
Cat Class ClassLoader is ru.ispras.j17.manual.fewmodules.together.dependent.CustomClassLoader@3fee733d
Meow
Same as in Java 17. Manual Loading (Java 17 style).
Same as in Java 17. Manual Loading (Java 17 style).
- In
module-info.javaof thedependencymodule you need to export the package with theCatclass, and inmodule-info.javaof thedependentmodule you need to specify the dependency on thedependencymodule:
// dependency/src/module-info.java
module manual.fewmodules.together.depedency {
exports ru.ispras.j17.manual.fewmodules.together.dependency;
}// dependent/src/module-info.java
module manual.fewmodules.together.dependent {
requires manual.fewmodules.together.dependency;
}.jpg)