Task: load any application class using a custom class loader (CustomClassLoader
) in Java 8 style (without module-info.java
).
Project with three classes:
Main
- a class containing themain
method, where an instance of theCustomClassLoader
class is created, theCat
class is loaded using it, creating an instance of the classCat
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.
Using classpath
:
java17 -cp . ru.ispras.j17.manual.onemodule.j8style.Main
or
java17 -jar java8style-1.0.jar
Output:
Main Class Module is unnamed module @99e937b
Cat Class Module is unnamed module @6d6f6e28
Main Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@531d72ca
Cat Class ClassLoader is ru.ispras.j17.manual.onemodule.j8style.CustomClassLoader@15db974
Meow
Using modulepath
:
java17 -p . -m java8style
Output:
Main Class Module is module java8style
Cat Class Module is unnamed module @3a71f4dd
Main Class ClassLoader is jdk.internal.loader.ClassLoaders$AppClassLoader@28d93b30
Cat Class ClassLoader is ru.ispras.j17.manual.onemodule.j8style.CustomClassLoader@5ca881b5
Meow
- When a
CustomClassLoader
is created, its parent becomesjdk.internal.loader.ClassLoaders$AppClassLoader
; - All classes will be under
unnamed module
if launched usingclasspath
. Experimentally, it was possible to find out that each class loader is related to two modules: firstly, as a class, it refers to the class loader module that loaded this class, and secondly, it has its own unnamed module (which can be obtained using the methodgetUnnamedModule
), which will contain all the classes that it will load on its own. Therefore, in this example, two unnamed modules appear: the first is loaded by the system loader and theMain
class is located there, and the second is loaded by theCustomClassLoader
loader, where theCat
class is already located. - If we run the
java8style-1.0.jar
file, then using the-p
and-m
options (usingmodulepath
), we will get an Automatic Module with the namejava8style
, which is implicitly obtained by the algorithm from documentation forModuleFinder
.
CustomClassLoader
gets some system classes to be loaded first, for example classes fromjava.*
packages. If you try to load a class from thejava.*
package, the JVM will throwjava.lang.SecurityException: Prohibited package name: java.*
;