First, let's take a look at the differences between bytecode and class files:
We know that when creating a java object, JVM will load the bytecode corresponding to this object into the memory, the original information of this bytecode is stored in the directory specified by classpath (that is, the bin directory of the newly created Java project. class file. the class file is imported to the hard disk. After some processing, it becomes a bytecode and is loaded into the memory.
The following is a simple example:
Package com. loadclass. demo; import java. util. date; import java. util. list;/*** test class * @ author Administrator */public class ClassLoaderTest {@ SuppressWarnings ("rawtypes") public static void main (String [] args) {// name of the classloader that outputs ClassLoaderText: System. out. println ("Name of the ClassLoaderText Class Loader:" + ClassLoaderTest. class. getClassLoader (). getClass (). getName (); System. out. println ("Name of the System Class Loader:" + System. class. getClassLoade R (); System. out. println ("Name of the listclass Loader:" + List. class. getClassLoader (); ClassLoader cl = ClassLoaderTest. class. getClassLoader (); while (cl! = Null) {System. out. print (cl. getClass (). getName () + "->"); cl = cl. getParent ();} System. out. println (cl );}}Output result:
We can see that the ClassLoaderTest class is loaded by the AppClassLoader class loader. Next, let's take a look at the class loaders in JVM and explain the running results.
Class loaders in Java virtual machines:
Multiple class loaders can be installed in the Java Virtual Machine. By default, the system has three major class loaders. Each class is responsible for loading classes at specific locations:
BootStrap,ExtClassLoader,AppClassLoader
The class loader is also a Java class, because the class loader of the Java class itself is also to be loaded by the class loader. Obviously, the First Class Loader must be not a Java class, which is exactly BootStrap, c/C ++ code has been encapsulated into the JVM kernel, while ExtClassLoader and AppClassLoader are Java classes.
Let's take a look at the property structure of the Class Loader:
All class loaders in the Java Virtual Machine are organized in a tree with parent-child relationship. when instantiating each class loader object, you need to specify a parent class loader object for it or use the system class loader as its parent class by default.
The delegate mechanism of the Class Loader:
When the Java Virtual Machine loads the first class, which class loader is dispatched to load the class?
(1 ). first, the class loader of the current Thread loads the first class in the Thread (the class loader of the current Thread: There is a get/setContextClassLoader (ClassLoader cl) in the Thread class); method, attackers can obtain or specify the class loaders in this thread)
(2) If Class A references Class B, the Java Virtual Machine will use the class loader of Class A to load Class B.
(3) You can also directly call the ClassLoader. loadClass (String className) method to specify a class loader to load a class.
When each class loader loads a class, it first delegates it to its parent class loader. When all ancestor class loaders are not loaded to the class, they return to the initiator class loader and cannot load the class, it will throw ClassNotFoundException, instead of looking for the son of the initiator class loader, because there is no getChild () method. For example, see MyClassLoader-> AppClassLoader-> Ext-> ClassLoader-> BootStrap. the custom MyClassLoader1 will first be delegated to the AppClassLoader, The AppClassLoader will be delegated to the ExtClassLoader, And the ExtClassLoader will be delegated to the BootStrap. At this time, the BootStrap will load. If the load is successful, it will end. If the loading fails, it will be handed over to ExtClassLoader for loading. If the ExtClassLoader is loaded successfully, it will end. If the loading fails, it will be handed over to AppClassLoader for loading. If the loading succeeds, it will end. If the loading fails, it is handed to the custom MyClassLoader1 Class Loader for loading. If the loading fails, the ClassNotFoundException exception is reported and the process ends.
Explain the previous running results based on the hierarchical structure chart of the class loader and the principle of delegated loading.
Because System, List, Map, and other systems provide jar classes in rt. jar, so it is loaded by the BootStrap class Loader. Because BootStrap is an ancestor class, not written in Java, it is printed that the class is null.
The output of the ClassLoaderTest class is also clear.
Now let's try again to verify the above conclusion:
First, package ClassLoaderTest. java into A. jar file (this step is simple)
Copy the. jar file to the Java/jre7/lib/ext/directory in the Java installation directory.
At this time, you are running the ClassLoaderTest class. The result is as follows:
The ClassLoaderTest class loader is changed to ExtClassLoader. At this time, the above conclusion is correct, because ExtClassLoader loads jre/ext /*. jar: first, the AppClassLoader Class Loader sends a request to ExtClassLoader, and then ExtClassLoader sends the request to BootStrap. However, BootStrap does not find the ClassLoaderTest class, so it is handed to ExtClassLoader for processing, in this case, ExtClassLoader finds the ClassLoaderTest class in my_lib.jar, so it loads and ends.
In fact, the benefit of using this tree-like class loading mechanism is:
It is able to uniformly load management classes. First, it is handed over to the upper-level. If the upper-level has the upper-level, it is loaded. In this way, if the class has already been loaded, at this time, when loading it, you only need to take it and use it again.
Next let's take a look at how to define our own class loader MyClassLoader:
You can define a class loader by yourself. to mount the class loader you have defined to the system class loader tree, you can specify the parent in the ClassLoader constructor. If it is not specified, use the default parent.
Here we can see that the default parent is obtained using the getSystemClassLoader method. The source code of this method is not found, so we can only test it through the code.
System. out. println ("Default class Loader:" + ClassLoaderTest. class. getClassLoader (). getSystemClassLoader ());The input result is:
Therefore, it is reasonable to mount the custom class loader to the lowest-end AppClassLoader of the system class loader by default.
The custom Class Loader must inherit the abstract class ClassLoader and then override it.FindClassIn fact, there is another internalLoadClassMethod andDefineClassMethods. The functions of these two methods are as follows:
Source code of the loadClass method:
public Class
loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); }Let's take a look at the source code of the loadClass (name, false) method:
Protected Class
LoadClass (String name, boolean resolve) throws ClassNotFoundException {// Add the lock for synchronous processing, because it may be that multiple threads are loading the class synchronized (getClassLoadingLock (name) {// check, whether the Class has been loaded. if it has been loaded, Class c = findLoadedClass (name) is not loaded; if (c = null) {long t0 = System. nanoTime (); try {// if the parent of the custom class loader is not null, call the loadClass of the parent to load the class if (parent! = Null) {c = parent. loadClass (name, false);} else {// if the parent of the custom class loader is null, call the findBootstrapClass method to find the class, is the Bootstrap Class Loader c = findBootstrapClassOrNull (name) ;}} catch (ClassNotFoundException e) {// ClassNotFoundException thrown if class not found // from the non-null parent class loader} if (c = null) {// If still not found, then invoke findClass in order // to find the class. long t1 = System. nanoTime (); // if the parent fails to load the class, call your findClass method to load c = findClass (name); // this is the defining class loader; record the stats sun. misc. perfCounter. getParentDelegationTime (). addTime (t1-t0); sun. misc. perfCounter. getFindClassTime (). addElapsedTimeFrom (t1); sun. misc. perfCounter. getFindClasses (). increment () ;}}if (resolve) {resolveClass (c);} return c ;}}In the loadClass code, we can also see the principle of the class loading mechanism. Here we also use this method findBootstrapClassOrNull. Let's take a look at the source code:
private Class findBootstrapClassOrNull(String name) { if (!checkName(name)) return null; return findBootstrapClass(name); }
Check whether the name is correct and call the findBootstrapClass method. However, the findBootstrapClass method is a native local method and does not see the source code. However, you can guess that the Bootstrap class loader is used to load classes, we cannot rewrite this method either, because if we rewrite this method, it will destroy this delegation mechanism. We also need to write a delegation mechanism by ourselves, which is very painful.
DefineClass: This method is very simple. It is used to program a class object in the byte array of the class file. This method cannot be rewritten. The internal implementation is implemented in the C/C ++ code.
The findClass method finds the class file based on the name and is used in the loadClass method. Therefore, we can only rewrite this method, as long as we find the class file in this method, then return a Class Object using the defineClass method.
The execution process of these three methods is: Each Class Loader: loadClass-> findClass-> defineClass
The previous knowledge is now available.
First, let's take a look at the class to be loaded: ClassLoaderAttachment. java:
Package com. loadclass. demo; import java. util. date;/*** loading class * @ author Administrator */public class ClassLoaderAttachment extends Date {private static final long serialVersionUID = 8627644427315706176L; // print data @ Overridepublic String toString () {return "Hello ClassLoader! ";}}Output a line in this class: compile it into ClassLoaderAttachment. class
Let's take a look at the custom MyClassLoader. java:
Package com. loadclass. demo; import java. io. byteArrayOutputStream; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. inputStream; import java. io. outputStream;/*** custom class Loader * @ author Administrator */public class MyClassLoader extends ClassLoader {// class to be loaded. class file directory private String classDir; // construction method without parameters, used for class. newInstance () constructs object using public MyClassLoader () {} public MyClassLoader (String classDir) {this. classDir = classDir;} @ SuppressWarnings ("deprecation") @ Overrideprotected Class
FindClass (String name) throws ClassNotFoundException {// path of the class file String classPathFile = classDir + "/" + name + ". class "; try {// decrypt the class file FileInputStream FD = new FileInputStream (classPathFile); ByteArrayOutputStream bos = new ByteArrayOutputStream (); encodeAndDecode (FS, bos ); byte [] classByte = bos. toByteArray (); // converts a byte into a classreturn defineClass (classByte, 0, classByte. length);} catch (Exception e) {E. printStackTrace ();} return super. findClass (name);} // test the ClassLoaderAttachment. the class file is encrypted and written to the public static void main (String [] args) throws Exception in the class_temp directory of the Project {// configure the running parameter String srcPath = args [0]; // ClassLoaderAttachment. class Original path String desPath = args [1]; // ClassLoaderAttachment. class output path String desFileName = srcPath. substring (srcPath. lastIndexOf ("\") + 1); String desPathFile = desPath + "/" + desFil EName; FileInputStream FCM = new FileInputStream (srcPath); FileOutputStream fos = new FileOutputStream (desPathFile); // encodeAndDecode (FS, fos) is encrypted to the class. close (); fos. close ();}/*** encryption and decryption algorithm * @ param is * @ param OS * @ throws Exception */private static void encodeAndDecode (InputStream is, OutputStream OS) throws Exception {int bytes =-1; while (bytes = is. read ())! =-1) {bytes = bytes ^ 0xff; // The OS. write (bytes );}}}This class defines an encryption and decryption algorithm. It is very simple, that is, the byte and oxff can be different or different, and this algorithm can be used for encryption and decryption, it's amazing!
Of course, we need to first perform the ClassLoaderAttachment operation. the class-encrypted file is stored, that is, executed in the main method. Here I create a new class_temp folder in the project to encrypt the encrypted class file:
Values are assigned in the form of parameters. Therefore, when running MyClassLoader, configure the input parameters: Right-click MyClassLoader-> run as-> run operations
The first parameter is ClassLoaderAttachment. the Source Path of the class file. The second parameter is the directory stored after encryption. After running MyClassLoader, refresh the class_temp folder and the ClassLoaderAttachment is displayed. this is an encrypted class file.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + z8LD5sC0v7TSu8/CsuLK1MDgo7o8L3A + CjxwPjxwcmUgY2xhc3M9 "brush: java;"> package com. loadclass. demo; import java. util. date; import java. util. list;/*** test class * @ author Administrator */public class ClassLoaderTest {@ SuppressWarnings ("rawtypes") public static void main (String [] args) {// name of the classloader that outputs ClassLoaderText: System. out. println ("Name of the ClassLoaderText Class Loader:" + ClassLoaderTest. class. getClassLoader (). getClass (). GetName (); System. out. println ("Name of the System Class Loader:" + System. class. getClassLoader (); System. out. println ("Name of the listclass Loader:" + List. class. getClassLoader (); System. out. println ("Default Class Loader:" + ClassLoaderTest. class. getClassLoader (). getSystemClassLoader (); ClassLoader cl = ClassLoaderTest. class. getClassLoader (); while (cl! = Null) {System. out. print (cl. getClass (). getName () + "->"); cl = cl. getParent ();} System. out. println (cl); try {Class classDate = new MyClassLoader ("class_temp "). loadClass ("ClassLoaderAttachment"); Date date = (Date) classDate. newInstance (); // name of the loader that outputs the ClassLoaderAttachment class: System. out. println ("ClassLoader:" + date. getClass (). getClassLoader (). getClass (). getName (); System. out. println (date);} catch (Exception e1) {e1.printStackTrace ();}}}Run the ClassLoaderTest class. The running result is as follows:
The ClassLoaderAttachment class loader is our own class loader MyClassLoader, And the Hello ClassLoader field is also output.
Don't think it's over. There are still a lot of problems here. Let's take a look at the problem, but there are still many things to understand. First, let's take a look at it, according to the class loading mechanism we mentioned earlier, we should first hand it to the parent class loader. AppClassLoader-> ExtClassLoader-> BootStrap, ExtClassLoader and BootStrap did not find ClassLoaderAttach. class, but the AppClassLoader class loader should be able to find it. Why? In this case, the full name (including the package name) needs to be passed when the loadClass method uses the system class loader. If we pass ClassLoaderAttachment, The ClassLoaderAttachment cannot be found for the AppClassLoader, so the MyClassLoader is still processing, if you don't believe it, try:
Now
Class classDate = new MyClassLoader("class_temp").loadClass("ClassLoaderAttachment");Changed:
Class classDate = new MyClassLoader("class_temp").loadClass("com.loadclass.demo.ClassLoaderAttachment");Result running:
At this time, the loader is AppClassLoader, so pay attention to the parameters passed by the loadClass method.
At this point, we seem to have not tested our encrypted class file. Now we will use ClassLoaderAttachment in the project directory. delete the class and delete the ClassLoaderAttachment encrypted in class_temp. copy the class and run the following command:
At this time, an error will be reported. The improper magic number error (the first six bytes of the class file are magic numbers used to identify the class file). This is correct because of ClassLoaderAttachment. this error is reported because AppClassLoader does not recognize the encrypted class file. Only the class Loader we have defined can be used for decryption. Now, I have finished talking about it. It took me a long morning to write big data. It was very troublesome!
Note two problems:
1. this may occur when the ClassLoaderTest class is not executed. This is because the ClassLoaderTest class is broken down during the first test. jar is put in the jre directory, So if you modify the ClassLoaderTest class subsequently, the operation will be ineffective, because the class it loads is still the ClassLoaderTest class in the jar in jre, so you should delete the jar in jre.
2. The ClassLoaderAttachment file will be compiled into the. class file as long as it is saved, so you should pay attention when copying the ClassLoaderAttachment. class file.