This article is the author in the study of Java class loading process, collation of experience, mutual encouragement!
The meaning of class loading
Simple concept:
Reads the binary data from the Java class's. class file into memory and places it in the method area of the run-time data area.
When does class loading occur?
Local system loading;
Agent loading, such as spring's AOP dynamic agent;
Load from the jar package;
Wait, wait.
Introduction to ClassLoader class structure
ClassLoader is an abstract class with the following core methods:
DefineClass (): The purpose is to parse the byte stream into a class object that the JVM can recognize.
Findclass (): This method supports overloading, used in conjunction with DefineClass (), to obtain the bytecode of a class object. The implication of this approach is that we can instantiate objects not only through class files, but also in other ways, such as bytecode files obtained from the network, and there may be corresponding cryptographic rules.
LoadClass (): This method supports overloading to get the class object that loads the class.
Resolveclass (): Implements the class to which the JVM is linked, this method calls the local method and cannot be overloaded.
The life cycle of class classes
This life cycle corresponds to the specific method of the ClassLoader class:
Loading: LoadClass (), Findclass (), DefineClass ()
Connectivity: Includes validation, preparation, parsing: resolveclass () Local native method
Initialize: The JVM is responsible for
Class loading mechanism (parental delegation)
Concept Introduction:
Approximate ClassLoader classification:
- Bootstrap ClassLoader: A class library that is responsible for loading stored in jdk\jre\lib (JDK represents JDK's installation directory, below), or in the path specified by the-xbootclasspath parameter, and can be recognized by the virtual machine
- Extclassloader: A class that is responsible for loading the Jdk\jre\lib\ext directory, or all class libraries in the path specified by the JAVA.EXT.DIRS system variable (such as javax.), developers can use the Extension class loader directly
- Appclassloader: is responsible for loading the class specified by the user class path (ClassPath), whose parent class is Extclassloader
Experience:
There is no inheritance relationship between the parent loader and the child loader in the Java class relationship;
Implementation of its own class loader, whether it is directly implemented abstract class ClassLoader, or inherit other subclasses, the parent loader is appclassloader;
How the class loads
1. When the command line starts the application, it is loaded by the JVM initialization
2. Dynamic loading via Class.forName () method
3. Dynamic loading via Classloader.loadclass () method
Class.forName () and the Classloader.loadclass () difference
Class.forName (): Loads the class's. class file into the JVM, also interprets the class, and executes the static block in the class;
Classloader.loadclass (): The only thing to do is to load the. class file into the JVM, not to execute the contents of static, only to execute the static block in Newinstance.
The Class.forName (name,initialize,loader) parameter function can also control whether static blocks are loaded. And only call the Newinstance () method using the call constructor to create the object of the class
Application practice to implement custom ClassLoader
Based on the above analysis of the ClassLoader, the case for customizing the ClassLoader is as follows:
- You need to look for a custom class file under a custom path
- Special handling of the classes we want to load, such as byte codes for classes that are transmitted over the network, can be encrypted, and the bytecode for this class needs to be implemented in our custom ClassLoader.
- Implementing a hot deployment of a class
From the above analysis we can also get, custom ClassLoader implementation ideas can be inherited ClassLoader class, rewrite Findclass () to implement, of course you can also rewrite LoadClass (), but the default loadclass () is to implement the class-loaded parental-delegation pattern, unless you want to break the parental-delegation pattern, or else you don't rewrite it.
Here is a demo of the test custom ClassLoader I wrote in this machine:
/*** The class file load under the custom path * @Auther: [email protected] * @Date: 2018/5/31 19:34 * @Description:*/ Public classPathclassloaderextendsClassLoader {PrivateString ClassPath; PublicPathclassloader (String classPath) { This. ClassPath =ClassPath; } PrivateString PackageName = "Com.trey.classloader.Test"; protectedClass<?> Findclass (String name)throwsClassNotFoundException {if(Packagename.startswith (name)) {byte[] Classdata =getData (name); if(Classdata = =NULL) { Throw Newclassnotfoundexception (); } Else{System.out.println ("Current class loader:" + This. GetClass (). getClassLoader (). toString ()); returnDefineClass (name, Classdata, 0, classdata.length); } } Else { return Super. LoadClass (name); } } Private byte[] GetData (string name) {string path= ClassPath + File.separatorchar + name.replace ('. ', File.separatorchar) + ". Class"; Try{InputStream is=NewFileInputStream (path); Bytearrayoutputstream Stream=NewBytearrayoutputstream (); byte[] buffer =New byte[2048]; intnum = 0; while(num = is.read (buffer))! =-1) {stream.write (buffer,0, num); } returnStream.tobytearray (); } Catch(IOException e) {e.printstacktrace (); } return NULL; }}
Implementing a hot deployment of a class
This is a summary exercise of the class loading learning for your own arrangement. Here's what you're going to accomplish:
- Implement a server service that listens for updates to all class files in a specific directory
- When a class file update occurs, it is loaded with a custom ClassLoader
Java class loading ClassLoader learning experience