Task: load application classes using a custom class loader (CustomClassLoader
) in Java 8 style (with module-info.java
).
Modules (declared via module-info.java
):
auto.onemodule.j17style
:Main
- a class containing amain
method creating an instance of theCat
class and calling theCat::talk
method;Cat
- loadable class with thetalk
method, which prints the string "Meow" tostdout
;CustomClassLoader
- a class that is an implementation of a custom class loader.
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
classpath
the results are the same as in [[Java 17. Auto Loading (Java 8 style)]].
Using modulepath
:
java17 -Djava.system.class.loader=ru.ispras.j17.auto.onemodule.j17style.CustomClassLoader \
-p . -m auto.onemodule.j17style
Output:
Error occurred during initialization of VM
java.lang.Error: class java.lang.ClassLoader (in module java.base) cannot access class ru.ispras.j17.auto.onemodule.j17style.CustomClassLoader (in module auto.onemodule.j17style) because module auto.onemodule.j17style does not export ru.ispras.j17.auto.onemodule.j17style to module java.base
We get an error because the java.base
module cannot access the CustomClassLoader
class. Solved by simply exporting the package to module-info.java
:
// module-info.java
module auto.onemodule.j17style {
exports ru.ispras.j17.auto.onemodule.j17style to java.base;
}
New output:
Main Class Module is module auto.onemodule.j17style
Cat Class Module is module auto.onemodule.j17style
System ClassLoader is ru.ispras.j17.auto.onemodule.j17style.CustomClassLoader@76ed5528
Main Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@4554617c
Cat Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@4554617c
Meow
- Regarding Java 17. Auto Loading (Java 8 style) is different with the
module name
manual.onemodule.j17style
in thejar
file, which is anchored withmodule-info .java
, so this module is considered an Application Module, and not an Automatic Module.
Same as in Java 17. Auto Loading (Java 8 style).