Read deep understanding of Java virtual machines-Part 2: Virtual Machine Loading Mechanism,
I. class loading processExecution time:Compile the program --> execute the program (JVM startup, program running), class loading occurs during the program running
Stages:Loading, connection (verification, preparation, parsing), initialization, use, and uninstallation
Execution sequence: Generally, the execution is performed in sequence according to the preceding stages, but there are cross-nodes between them. Load --> verify (File Format) --> Continue loading --> parse --> verify (metadata, bytecode) --> prepare --> initialize
Participating roles:Class file, Java virtual machine, Class Loader
/** The Bootstrap ClassLoader (startup Class Loader) of HotSpot is located inside the VM (implemented by C ++), and other class loaders are external to JVM (implemented by Java )*/
Ii. Description-various stages Loading phase: Common classes/interfaces, array classes (the component type is basic, such as int [] []): Get, convert, create, triggerGet -- the Class Loader loads the Class file (specify the path + file name --> confirm the "fully qualified name" --> get the Class file (Binary byte stream unrelated to the platform )) conversion-bytecode is converted to a certain format and stored in the Method Area creation-the method area generates a java that represents this class. lang. class Object trigger -- when loading, loading class A extends B ----> Class <B> private Class <Person> class ----> Class <Person> class c = Person. getClass (); ----> Class <Person>
1. About "Class Loader" and "generated Class Object ":
1) Class Loader
Bootstrap Loader (start class Loader), Extended Loader (standard extension class Loader ExtClassLoader), AppClass Loader (system class Loader/Application Class Loader AppClassLoader)
Start the Class Loader:
Objective: to load the bytecode files (such as rt. jar and basic classes such as java. lang. Object) in the java_home \ lib directory, which files and the loading sequence are specific?
Method: load System. getProperty ("sun. boot. class. path ") the specified path or jar. You can also specify the search path when using Java to run the program, for example, java-Djava. ext. dirs = d: \ projects \ testproj \ classes HelloWorld reference: http://www.cnblogs.com/ITtangtang/p/3978102.htm
Standard extension class loader:
Objective: To load the bytecode file under the java_home \ lib \ ext directory
Method: load the path or jar specified by System. getProperty ("java. ext. dirs. When running a program using Java, you can also specify the search path, for example, java-Djava. ext. dirs = d: \ projects \ testproj \ classes HelloWorld
Result: <implementation class> sun. misc. Luncher @ ExtClassLoader -------- <inheritance relation> ClassLoader> URLClassLoader> AppClassLoader
Application Class Loader:
Method: load the path or jar specified by System. getProperty ("java. class. path. When running a program using Java, you can also add-cp to overwrite the original Classpath settings, for example, java-cp./lavasoft/classesHelloWorld
Result: <implementation class> sun. misc. Luncher @ AppClassLoader -------- <inheritance relationship> ClassLoader> URLClassLoader> AppClassLoader
Custom Class Loader:
Method: 1) inherit java. lang. classLoader and override the loadClass method; 2) inherit from java. lang. classLoader and override findClass method/** recommended after JDK1.2. For the reason, see the red section below */;
Related:
1 <1> java. lang. Object 2 1. getClass () 3 public final native Class <?> GetClass (); // get the Class object at runtime [through the local method] 4/** 5 * example: class-Test> main> 6 * Class c = Person. getClass (); 7 */8/** 9 * Implementation: 10*1) Virtual Machine startup 11*2) Virtual Machine class loading -- Test. class ---- loading stage: Method Area> external interface> new java. lang. class // Class <?> 12*3) VM class loading -- java. lang. object ---- [Test loading stage] triggers 13*3) VM class loading -- Person. class ---- [Test loading stage] triggers 14*4) The application starts 15*5) calls java. lang. classLoader> xxx1 (), xxx2 ()..... -- return the <Person> Class Object 16 */17 18 19 <2> java at runtime. Lang. classLoader20 1. loadClass (String name, boolean resolve)/** load the binary type of the specified name (including the package name), and specify whether to parse */21 loadClass (String name) 22 protected Class <?> FindClass (String name) throws ClassNotFoundException {// null Method 23 throw new ClassNotFoundException (name); 24} 25 protected Class <?> LoadClass (String name, boolean resolve) // get the Class Loader [via local method] 26 throws ClassNotFoundException27 {28 synchronized (getClassLoadingLock (name) {29 // First, check if the class has already been loaded30 Class c = findLoadedClass (name); 31 if (c = null) {32 long t0 = System. nanoTime (); 33 try {34 if (parent! = Null) {35 c = parent. loadClass (name, false); 36} else {37 c = findBootstrapClassOrNull (name); 38} 39} catch (ClassNotFoundException e) {40 // ClassNotFoundException thrown if class not found41 // from the non-null parent class loader42} 43 44 if (c = null) {45 // If still not found, then invoke findClass in order46 // to find the class.47 long t1 = System. nanoTime (); 48 c =FindClass (name );49 50 // this is the defining class loader; record the stats51 sun. misc. perfCounter. getParentDelegationTime (). addTime (t1-t0); 52 sun. misc. perfCounter. getFindClassTime (). addElapsedTimeFrom (t1); 53 sun. misc. perfCounter. getFindClasses (). increment (); 54} 55} 56 if (resolve) {57 resolveClass (c); 58} 59 return c; 60} 61} 62 63 64 65 66 <3> java. lang. class 67 1. getClassLoader () 68/** example: class-Test> main> 69 * Ob Ject o = new Object (); 70 * System. out. println (o. getClass (). getClassLoader (); 71 result> java. lang. nullPointerException 72 */73/** 74 * Returns the class loader for the class. 75 * This method will return null in such implementations if this class was loaded by the bootstrap class loader. 76 * if no classLoader is specified, the bootstrap classLoader (start class loader) is returned by default. Because the bootstrap classLoader77 * user cannot get the instance, returning null indicates that bootstrap c is returned. LassLoader 78 */79 native ClassLoader getClassLoader0 (); // get the Class Loader [through local method] 80 public ClassLoader getClassLoader () {81 ClassLoader cl = getClassLoader0 (); 82 if (cl = null) 83 return null; 84 SecurityManager sm = System. getSecurityManager (); 85 if (sm! = Null) {86 ClassLoader. checkClassLoaderPermission (cl, Reflection. getCallerClass (); 87} 88 return cl; 89}
2. Specify the classloader class
Class. forName (name, initialize, loader)
2) Relationship with "generated Class Object"
Only when a Class file is loaded by the same Class loader can it be determined to be equal ----> equal meaning: 1) not equal, multiple Class objects will be generated; equal, only one Class object is generated.
2) Only the same Class object, equals (), isAssignabaleFrom (), instanceof, and isInstance () returns the same result;
3) Parental Delegation Model
Link?
The upper level holds A reference of the lower level, which belongs to the has A relationship.
Division of labor? (Why is it "Parental appointment)
A Class Loader receives a class loading request. Instead of trying to load the class, it delegates the request to the class loader at the previous layer. Only when the upper-level loader cannot find the required class in the search range and the loading request cannot be completed, the lower-level loader will try to load it by itself.
Benefits?
Java classes have a level of priority along with their class loaders.
2. Load the "Class/interface" policy:
Non-array class/interface, array class (component type is basic type, such as int [] []):
Load and generate the java. lang. after the Class object, it will be identified as "loaded" on the "Class namespace" of the Class Loader (as discussed earlier, only when the same Class file corresponds to the same Class loader determines that the generated Class object is the same Class Object)
Array class (component type is reference type, such as Person [] []), non-array class/interface: recursively load component type, remove one dimension each time
Connection phase:
Verification-file format, metadata, bytecode
Preparation -- allocate and initialize the class variable in the Method Area
Example: verification phase during compilation (during class loading)-preparation period
Static int I = 20; generate the constantValue attribute, but it is not stored in constant 20. The regular method is used for preparation: initialization and memory allocation.
Result -----> none
Final static int I = 20; generate the constantValue attribute, coexist between 20 and constantValue, and obtain the corresponding constantValue for initialization.
Result -----> 20
Resolution-replace the symbolic reference of the runtime constant pool with a direct reference (pointing to the handle of the memory target). This process is also called "static binding/static connection"
Initialization Phase: (dynamic binding/dynamic connection) 1. execution time -- active reference (New, reflection, parent class, execution main class contains main method, call static method) * New--
Execute <Clinit> (), Execute <clinit> (),Execute the <client>,<Client>
1 // example (general questions) 2 public class Father {3 4 private static int I = 20; 5 static {6 System. out. println ("Father; (class constructor-before)" + I); 7 I = 50; 8 System. out. println ("Father; (class constructor-after)" + I); 9} 10 public Father () {11 System. out. println ("Father :( instance constructor)" + I); 13} 14 15} 16 17 18 19 public class Son extends Father {20 21 private static int I = 20; 22 static {23 System. out. println ("Son; (class constructor-before)" + I); 24 I = 50; 25 System. out. println ("Son; (class constructor-after)" + I); 26} 27 public Son () {28 System. out. println ("Son :( instance constructor)" + I); 30} 31} 32 33 34 35 public class Main {36 37 public static void main (String [] args) {38 new Son (); 39 40} 41 42} 43 44 // output: 45/** 46 * Father; (class constructor-before) 2047 * Father; (class constructor-after) 5048 * Son; (class constructor-before) 2049 * Son; (class constructor-after) 5050 * Father :( instance constructor) 5051 * Son: (instance constructor) 5052 */
2. Active and passive references Passive reference -- class loading will occur, but initialization will not -- Example: omitted