A. java file in Java is compiled, and a class file. class file is generated. The class file is stored in the hard disk as a binary bytecode. When we need to use or load a Java file into the JVM, the byte-code class file is read from the hard disk, and the class file is loaded into the JVM through the ClassLoader. In other words, all Java files are loaded into the JVM through the ClassLoader. Of course, the class loader is also a Java file. So how does the first ClassLoader load into the JVM? When the JVM is started, a local method Findbootstrapclass method is loaded to load the initial classloader,private native Class Findbootstrapclass (String name), This local method is written in C + +.
1. The system already has 3 kinds of loaders
1.1 booststrapclassloader (boot) load Rt.jar The following class (this loader is written in C + + and is not visible in general development)
1.2 Extclassloader Load Extclassloader The following class (the jar below the Ext folder)
1.3 Appclassloader Load Classpaht the following class
almost all of the classes we write are loaded into the JVM by appclassloader the loader.
2. Loading mechanism of class loader ( parental delegation mechanism )
each classloader has a corresponding parentclassloader.
2.1 System Class loader parent-child relationship
the father of the custom class loader is Appclassloader
Appclassloader's father was extclassloader.
Extclassloader's father was booststrapclassloader.
public class Testclassloader {public static void Main (string[] args) { ////Current object's ClassLoader ClassLoader loader = new Testclassloader (). GetClass (). getClassLoader (); The ClassLoader from the current object wants to find his various ancestors while (loader! = null) { System.out.println (Loader.getclass (). GetName ()); Loader = Loader.getparent (); } Know that finding the last ancestor is null System.out.println (loader);} } Output: Sun.misc.launcher$appclassloadersun.misc.launcher$extclassloadernull
the order in which class 2.2 loaders are loaded
The ClassLoader is loaded down from the root
That is boot-"Exiclassloader-" Appclassloader
when a class needs to be loaded, it is first passed by the Appclassloader loader to its father, Extclassloader, and then Extclassloader passed on to his father, boot.
when Boot discovers that he has a corresponding class within the load range, it is loaded into the JVM, otherwise it is handed to the son Extclassloader to handle.
Extclassloader again in his load range class to find there is no corresponding class, there is loaded into the JVM, did not hand over to appclassloader processing.
Appclassloader again in the classpath path to find the corresponding class, found on the load, no report exception.
cause: This ensures that one of the classname in the JVM corresponds to the same class, because it is loaded down from the root.
avoid repeated loading, when the father has loaded the class, there is no need for the child classloader to load again.
loading from the bottom up may cause a classname to correspond to several classes in the JVM. Maybe we'll define our own class loader and our own load range.
When you define classes that are loaded in their respective scopes and find the classes that need to be loaded, they may all load, causing a classname in the JVM to correspond to several different class
2.3 For example, we define a class loader to load the Java.lang.String class, so we cannot achieve our goal.
because the loading mechanism is loaded from top to bottom, when it is passed to boot above, it has been loaded into the JVM and cannot be loaded by our custom class loader.
However, we can definitely define a class loader ourselves to load the classes we specify.
3. How to customize a class load
first, we need to inherit Classloadar
then, we can't break the original class-loading mechanism (parent-delegation mechanism), so we can't overwrite the LoadClass method, we need to overwrite the Findclass method.
Finally, write the code of our ClassLoader in the Findclass method.
View Source code explanation:
Protected class<?> loadclass (String name, Boolean resolve) throws classnotfoundexception{synchronized (GETCLA Ssloadinglock (name)) {//first check if the class name corresponds to whether class C = Findloadedclass (name) has been loaded; If not loaded if (c = = null) {Long T0 = System.nanotime (); Try to get Parentclassloader to load try {if (parent! = NULL) {//when parent is not null, let par ent to LoadClass C = Parent.loadclass (name, false); } else {//when the parent is null, the Local method C = findbootstrapclassornull (name) is dispatched; }} catch (ClassNotFoundException e) {}//when Parentclassloader is not loaded if (c = = null) {Long T1 = System.nanotime (); Dispatching Findclass method to load C = findclass (name); }} if (resolve) {resolveclass (c); } return C; }}
4. For example
Goal: Customize a class loader with our specified path, passing the class that I encrypt.
Process: Locate the class file under the specified path, decrypt it, and load it into the JVM.
4.1 First define a class that needs to be encrypted and use it for testing
public class MyClass extends Date { @Override public String toString () { return ' Hello World '; }}
4.2 Encrypt the original class file
public static void Main (string[] args) throws Exception { string inputsrc = args[0];//the path and file name of the original class file in the String ou TPUTSRC = args[1];//The file path and filename stored after encryption fileinputstream FIS = new FileInputStream (INPUTSRC); FileOutputStream fos = new FileOutputStream (OUTPUTSRC); Call the cryptographic algorithm cypher (FIS, FOS); Fis.close (); Fos.close ();} /** * Cryptographic Decryption Function Method * * @param is * @param os * @throws ioexception */private static void Cypher (InputStream is, OutputStream o s) throws IOException { int b =-1; while ((b = Is.read ())! =-1) { //0 becomes 1, 1 becomes 0 os.write (b ^ 0xff);} }
4.3 writing our own ClassLoader
public class Myclassloader extends ClassLoader { //the path of the class to be loaded private String classsrc; Public Myclassloader () { } public Myclassloader (String classsrc) { this.classsrc = classsrc; } @Override protected class<?> findclass (String name) throws ClassNotFoundException { // Find the location of your own encrypted class file first String classfielname = classsrc + "\ \" + Name + ". Class"; try { FileInputStream fis = new FileInputStream (classfielname); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Allocation and decryption algorithm cypher (FIS, BAOs); Fis.close (); byte[] bytes = Baos.tobytearray (); Convert the read-out binary to class byte code return defineclass (null, Bytes, 0, bytes.length); } catch (Exception e) { E.printstacktrace (); } return Super.findclass (name);} }
4.4 Loading our encrypted classes into the JVM using our own classes
First use your own classloader to load our encrypted class file//Note that the class under the path of the loading classes in this place should be the location of the files we encrypt after class clazz = new Myclassloader ("e:/allworkspace/ Workspace1/classloadertest/bin/com/gusi/test "). LoadClass (" MyClass ");//through reflection, test our classloaderdate date = (date) Clazz.newinstance (); System.out.println (Date.tostring ());
A detailed explanation of ClassLoader in Java