This repository contains the code for all the examples from the article on Habr. Each example comes with its own README.md.
Each example demonstrates how class loaders are associated with classpath
/modulepath
. Examples using Java versions 8 and 17 are considered, where the main difference is the modular system that appeared in Java 9.
Examples:
- Java 8
- Java 17
- Manual
- One Module
- Few Modules
- Auto
- One Module
- Few Modules
- Manual
Each example uses just a few classes for demonstration purposes. Below are the features of each of them.
A class with a main
method, in which, depending on the example, either the simplest classes Cat
or Dog
are loaded, or instances of the simplest classes are created. At the end of the method, the talk
method is called on an instance of the simplest class.
Between instantiation and calling the talk
method, information about class loaders and/or the name of the modules to which the classes belong is printed.
A custom class loader that almost completely satisfies the delegation model, except that it first tries to load the class , and only then delegate to the parent loader.
Methods:
loadClass
:- First, an attempt is made to find a class among the loaded classes;
- Then an attempt is made to load the class yourself, if it is from the application;
- If the class is not from the application, then the loading is delegated to the ancestor.
findClass
: Loads the bytecode of a class (if found) and defines it as a class.
If you try to load a class from the java.*
package, the JVM will throw java.lang.SecurityException: Prohibited package name: java.*
. To determine that the class is from an application, it checks that binary name begins with ru.ispras
.
The simplest class to load with a single talk
method that prints the word "Meow" to stdout
.
The simplest class to load with a single talk
method that prints the word "Woof" to stdout
.