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 themainmethod, where an instance of theCustomClassLoaderclass is created, theCatclass is loaded using it, creating an instance of the classCatand calling theCat::talkmethod;Cat- loadable class with thetalkmethod, 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.Mainor
java17 -jar java8style-1.0.jarOutput:
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 java8styleOutput:
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
CustomClassLoaderis created, its parent becomesjdk.internal.loader.ClassLoaders$AppClassLoader; - All classes will be under
unnamed moduleif 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 theMainclass is located there, and the second is loaded by theCustomClassLoaderloader, where theCatclass is already located. - If we run the
java8style-1.0.jarfile, then using the-pand-moptions (usingmodulepath), we will get an Automatic Module with the namejava8style, which is implicitly obtained by the algorithm from documentation forModuleFinder.
CustomClassLoadergets 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.*;
.jpg)