Task: load application classes using a custom class loader (CustomClassLoader).
Project with three classes:
Main- a class containing amainmethod creating an instance of theCatclass and 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.
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.
java8 -Djava.system.class.loader=ru.ispras.j8.auto.CustomClassLoader -cp . ru.ispras.j8.auto.Main
or
java8 -Djava.system.class.loader=com.habr.j8.auto.CustomClassLoader -jar auto-1.0.jar
Output:
System ClassLoader is ru.ispras.j8.auto.CustomClassLoader@75b84c92
Main Class ClassLoader is ru.ispras.j8.auto.CustomClassLoader@75b84c92
Cat Class ClassLoader is ru.ispras.j8.auto.CustomClassLoader@75b84c92
Meow
- When a
CustomClassLoaderis created, its parent becomessun.misc.Launcher$AppClassLoader; - Since
CustomClassLoaderis a system class loader, all classes to be loaded are first delegated to it, it loads application classes, and the rest is transferred tosun.misc.Launcher$AppClassLoader.
- If you do not define a public constructor in
CustomClassLoader, the JVM initialization error will occur:
Error occurred during initialization of VM
java.lang.Error: java.lang.NoSuchMethodException: ru.ispras.j8.auto.CustomClassLoader.<init>(java.lang.ClassLoader)
