First Look at:
What is class loading: The JVM reads the class text into memory, passes the validation of the class file, parses it, initializes the process that eventually allocates memory in the JVM's heap and method area to form a type that can be used directly by the JVM.
Life cycle: 7 stages: Loading (load) verification (validate) preparation (Prepare) Resolution (connection) initialization (initialize) using (use) unloading (unload)
Load loading
This phase of the JVM completes the following actions:
First, the class loader reads the binary byte stream of the class through the full path qualified name of the class.
The class structure represented by the binary byte stream is then transformed into the method area of the run-time data area.
Finally, a Java.lang.Class instance representing this class is generated in the JVM heap (not an instance of this class)
Class Loader
Getting a binary stream of a class can be loaded using either the JVM's own class loader or its own write loader, a small step that is fully controllable. Different loaders can be read from various places: Zip Package jar Package, class file, network stream ... Read the binary byte stream of a class
The same source class loaded by the same loader is really the same. Different loaders load homologous class, not homogeneous! Instanceof to False
Class-Loaded Parental delegation model
Each loader is the first to delegate its own parent loader load class, if it does not load itself to load
The Java default class lookup loading order is top-down, and the tree-like structure
The intent of the parent delegation is to ensure that the most basic behavior in the Java type System is consistent and that the classes in the JDK are loaded first
There are four main types of loaders:
-
The JVM starts the ClassLoader bootstrap loader, implemented in C + + as part of the JVM (referring to Sun's hotspot only), and is responsible for loading the classes in the class library below Java_home/lib, which the JAVA program cannot reference.
-
The extension classloader extension Loader, implemented by the Sun.misc.launcher$extclassloader class, can be used in Java and is responsible for Java_home/lib/ext Loading of classes in the catalog and the Java.ext.dir Directory class library.
-
The Application class Loader application system Loader, implemented by Sun.misc.louncher$appclassloader, is responsible for loading classes in class libraries in the user classpath, which is the default loader if no custom loader is used!
-
The user-defined loader itself defines where to load the class's binary stream
1, the class loading process the Java program runs in memory, and when executed at the command line: the Java HelloWorld command, the JVM loads the Helloworld.class into memory and forms a class object helloworld.class. The process is the class loading process: 1, look for the JRE directory, look for Jvm.dll, and initialize the jvm;2, generate a Bootstrap Loader (boot class loader); 3, Bootstrap Loader automatic loading extended Loader (Standard extension class loader) and set its parent Loader to Bootstrap Loader. 4. Bootstrap Loader automatically loads Appclass Loader (System ClassLoader) and sets its parent Loader to extended Loader. 5, finally by Appclass Loader load HelloWorld class. 2, the class loader searches directories bootstrap, Extclassloader, Appclassloader are ClassLoader, Bootstrap is written in local code, and Extclassloader, Appclassloader are all written in Java, all in the Rt.jar. 1. Bootstrap Loader (startup ClassLoader): Loads the path or jar specified by the System.getproperty ("Sun.boot.class.path"). 2, Extended Loader (Standard extension class loader Extclassloader): Loads the path or jar specified by System.getproperty ("Java.ext.dirs"). When you run a program using Java, you can also specify its search path, for example: Java-djava.ext.dirs=d:\projects\testproj\classes HelloWorld3, Appclass Loader (System class loader Appclassloader): Loads the path or jar specified by System.getproperty ("Java.class.path"). When using Java to run a program, you can also add-CP to overwrite the original classpath settings, for example: JAVA-CP./lavasoft/classes HelloWorld Extclassloader and Appclassloader after the JVM is started, a copy is saved in the JVM, and the search path cannot be changed while the program is running. If you want to transport theWhen a class is loaded from another search path, a new class loader is generated. 3, class loader features 1, when you run a program, the specified class is always loaded by the Appclass Loader (System class loader). 2. When the class is loaded, each classloader will hand the load task to its parent, if the parent cannot find it, and then load it by itself. 3, Bootstrap Loader (startup class loader) is the top class loader, its parent loader is NULL.4, the class loader gets public class HelloWorld {public static void main (string[ ] args) {HelloWorld Hello = new HelloWorld (); Class C = Hello.getclass (); ClassLoader loader = C.getclassloader (); SYSTEM.OUT.PRINTLN (loader); System.out.println (Loader.getparent ()); System.out.println (Loader.getparent (). GetParent ()); }} Run Result: [Email protected][email protected]null from the above results can be seen, and did not get to Extclassloader's parent loader, because Bootstrap The Loader (startup ClassLoader) is implemented in C, and a determined return to the parent Loader is not found, so it returns NULL. 5, the class load class loading has three ways: 1, the command line starts the application time by the JVM initialization load 2, through the Class.forName () method dynamic load 3, through the Classloader.loadclass () method dynamic loading three way difference is larger, See an example: public class HelloWorld {public static void main (string[] args) throws ClassNotFoundException { ClassLoader loader =HelloWorld.class.getClassLoader (); SYSTEM.OUT.PRINTLN (loader); Use Classloader.loadclass () to load the class without executing the initialization block Loader.loadclass ("Test2"); Using Class.forName () to load the class, the initialization block//Class.forName ("Test2") is executed by default; Use Class.forName () to load the class and specify ClassLoader, which does not perform static block//Class.forName ("Test2", false, loader) when initializing; }} public class Test2 {System.out.println ("Static initialization block executed! "); }} to switch the loading mode separately, there will be different output results. 6, custom Classload to illustrate the problem, first look at the example: Package test; Import java.net.MalformedURLException; Import Java.net.URL; Import Java.net.URLClassLoader; public class Myclassloader {public static void main (string[] args) throws Malformedurlexception, Classnotfoundexc Eption, illegalaccessexception, instantiationexception {URL url = new URL ("File:/e:\\projects\\testscanne R\\out\\production\\testscanner "); ClassLoader Myloader = new URLClassLoader (New URL[]{url}); Class C = myloader.loadclass ("Test. Test3 "); System.out.println ("----------"); Test3 t3 = (Test3) c.newinstance (); }} public class Test3 {static initialization block of SYSTEM.OUT.PRINTLN ("Test3" executed! "); After the run:----------Test3 static initialization blocks are executed! Process finished with exit code 0 can see that the custom ClassLoader Myloader = new URLClassLoader (New Url[]{url}) has successfully loaded the class TEST3 into memory and passed The default construction method constructs the object Test3 t3 = (Test3) c.newinstance (); There is also an important point about ClassLoader: A class file loaded with the same classloader, with only one class instance. However, if the same class file is loaded with a different classloader, there will be two different ClassLoader instances (provided that two classloader cannot be used with the same parent class loader).
The mesh loading model of OSGi
Parental delegation is a recommended class loader implementation for Java designers and can be extended on a follow-up basis to customize the implementation mechanism of the ClassLoader.
OSGi's de facto Java modularity Standard, his custom classloader, can be a lot better for modularity and thermal deployment of modules: Replace a bundle with the bundle's class loader.
Classes beginning with java.* in OSGi are loaded by a parent-loading mechanism, while others are loaded by a peer-class loader, forming a net.
Verify Verification
Loading and authentication are cross-checked, verifying that the byte-code file represented by the binary stream is qualified, mainly judging from a few aspects:
File format: See the class file format in detail, after the file format verification of the byte stream to enter the method area to allocate memory for storage.
Metadata validation: Compliance with the Java language Specification
Bytecode validation: Analysis of data flow and control flow, which is the most complex step
Symbolic reference validation: When a symbolic reference is converted to a direct reference (parsing phase), detection of existence, accessibility validation of information other than the class itself
If you confirm that the code is safe and correct, you can use-xverify:none to turn off validation for most classes and speed up class load times
Prepare preparation
allocating memory to class variables (static adornments) in the method area
The value is then initialized, and if the class variable is a constant, it is assigned directly to the constant value otherwise the default 0 value of the Java type.
Parsing resolution
Refers to the process of replacing a symbolic reference within a constant pool with a direct reference.
Initialize initialization
This stage really starts executing Java code, static code blocks and setting the initial value of the variable to the value set by the programmer
Active referencing
There are only 5 cases in which the class is initialized immediately, called an active reference:
-
When the new object
-
Reads or sets the static field of the class (in addition to being final, having put the result in the static field of the constant pool at compile time) or invoking a static method of the class;
-
When a class is reflected using the Java.lang.reflect package method to invoke a class that has not been initialized
-
Initializes a class when it discovers that its parent class is not initialized, first initializes its parent class
-
The class containing the main method, when the JVM starts, it needs to specify an execution main class, the JVM initializes the class first
Other references to classes are referred to as passive references, and no initialization action is performed when the class is loaded
The initialization order of subclasses when inheriting from a parent class
1. Initialize the static variables and blocks of the parent class first, in the order in which they appear
2. Initialize the subclass's static variables and blocks, in order of occurrence
3. Initialize the normal variable of the parent class, calling the constructor of the parent class
4. Initialize the generic variable of the subclass and call the constructor of the child class
The initialization process of a class occurs at the moment:
1. T is a class, when an instance of T is created, that is t t = new t ();
2. When a static method of T is called, it is T.staticfield ();
3. When the static property of T is assigned, T.staticfield = O;
4. When a static property of T is used, that is, Object o = T.staticfield; But it is not a constant.
5. T is a top level class, and an Assert statement lexically nested
1, the class loading process the Java program runs in memory, and when executed at the command line: the Java HelloWorld command, the JVM loads the Helloworld.class into memory and forms a class object helloworld.class. The process is the class loading process: 1, look for the JRE directory, look for Jvm.dll, and initialize the jvm;2, generate a Bootstrap Loader (boot class loader); 3, Bootstrap Loader automatic loading extended Loader (Standard extension class loader) and set its parent Loader to Bootstrap Loader. 4. Bootstrap Loader automatically loads Appclass Loader (System ClassLoader) and sets its parent Loader to extended Loader. 5, finally by Appclass Loader load HelloWorld class. 2,directories that the class loader searches for separately
Bootstrap, Extclassloader, Appclassloader are Class loaders, Bootstrap are written in native code, and Extclassloader and Appclassloader are all written in Java, are in the Rt.jar.
1. Bootstrap Loader (startup ClassLoader): Loads the path or jar specified by the System.getproperty ("Sun.boot.class.path"). 2, Extended Loader (Standard extension class loader Extclassloader): Loads the path or jar specified by System.getproperty ("Java.ext.dirs"). When you run a program using Java, you can also specify its search path, for example: Java-djava.ext.dirs=d:\projects\testproj\classes HelloWorld3, Appclass Loader (System class loader Appclassloader): Loads the path or jar specified by System.getproperty ("Java.class.path"). When using Java to run a program, you can also add-CP to overwrite the original classpath settings, for example: JAVA-CP./lavasoft/classes HelloWorld Extclassloader and Appclassloader after the JVM is started, a copy is saved in the JVM, and the search path cannot be changed while the program is running. If you want to load a class from another search path at run time, a new classloader will be generated. 3, class loader features 1, when you run a program, the specified class is always loaded by the Appclass Loader (System class loader). 2. When the class is loaded, each classloader will hand the load task to its parent, if the parent cannot find it, and then load it by itself.
3, Bootstrap Loader (startup class loader) is the top class loader, its parent loader is NULL.4, the class loader gets
PublicclassHelloWorld {
PublicStaticvoidMain (string[] args) {
HelloWorld Hello =NewHelloWorld ();
Class C = Hello.getclass ();
ClassLoader loader = C.getclassloader ();
SYSTEM.OUT.PRINTLN (loader);
System.out.println (Loader.getparent ());
System.out.println (Loader.getparent (). GetParent ());
}
}
Operation Result:
[Email protected]
[Email protected]
Null
As can be seen from the above results, it is not obtained to Extclassloader's parent Loader, because Bootstrap Loader (startup ClassLoader) is implemented in C language, cannot find a definite way to return the parent Loader, then returns NULL.
5, the class load class loading has three ways: 1, the command line starts the application time by the JVM initialization load 2, through the Class.forName () method dynamic load 3, through the Classloader.loadclass () method dynamic loading three way difference is larger, See an example to understand: PublicclassHelloWorld {
PublicStaticvoidMain (string[] args)throwsclassnotfoundexception {
ClassLoader loader = HelloWorld.class. getClassLoader ();
SYSTEM.OUT.PRINTLN (loader);
//Use Classloader.loadclass () to load the class without executing the initialization block
Loader.loadclass ("Test2");
//using Class.forName () to load the class, the initialization block is executed by default
//Class.forName ("Test2");
//Use Class.forName () to load the class and specify ClassLoader, which does not perform static block initialization
//Class.forName ("Test2", false, loader);
}
} PublicclassTest2 {
Static{
System.out.println ("Static initialization blocks are executed!" ");
}
} switch the loading mode separately, there will be different output results. 6, custom Classload to illustrate the problem, take a look at the example first: PackageTest
ImportJava.net.MalformedURLException;
ImportJava.net.URL;
ImportJava.net.URLClassLoader;
PublicclassMyclassloader {
PublicStatic voidMain (string[] args)throwsMalformedurlexception, ClassNotFoundException, Illegalaccessexception, instantiationexception {
URL url =NewURL ("File:/e:\\projects\\testscanner\\out\\production\\testscanner");
ClassLoader Myloader =NewURLClassLoader (NewUrl[]{url});
Class C = Myloader.loadclass ("Test. Test3 ");
System.out.println ("----------");
Test3 t3 = (Test3) c.newinstance ();
}
} PublicclassTEST3 {
Static{
System.out.println ("The static initialization blocks of the TEST3 are executed!" ");
}
After running:----------
Static initialization blocks of TEST3 are executed!
Process finished with exit code 0 can see that the custom ClassLoader Myloader = new URLClassLoader (New Url[]{url}) has successfully loaded the class TEST3 into memory and passed The default construction method constructs the object Test3 t3 = (Test3) c.newinstance (); There is also an important point about ClassLoader: A class file loaded with the same classloader, with only one class instance. However, if the same class file is loaded with a different classloader, there will be two different ClassLoader instances (provided that two classloader cannot be used with the same parent class loader).
Java class loading process, understand?