1. loading, verification, preparation, initialization, is determined by the order of unloading, the sequence parsing is uncertain, it can be resolved before the initialization phase may be (dynamically loaded) after the initialization;
1> Load: by definition the full class name of such a binary byte stream, the byte stream static storage structure represented by the runtime data structures into the method area, then generate a stack java.lang.Class objects, as a method of accessing the inlet region
2> Verify: Verify that the data loaded in line with the agreed rule javac compiler (verification file format, metadata validation, bytecode verification, verification of symbolic references);
3> Preparation: static class variable is assigned an initial value (not including instance variables), the set value is set will be executed in the initialization phase of the class, instance variables of the object instance is assigned along with an object in the heap java in.
4> Analysis: The symbolic constant pool reference becomes a direct reference (reference symbol is a set amount literally follow the naming rules unrelated to realize the virtual machine memory layout, the goal is not necessarily symbolic references are loaded into memory to; direct reference: direct reference may be a pointer, or a relative offset to the target can handle simple positioning is associated with the internal layout, and different virtual machine instances out of direct reference is generally not the same), symbolic references require further in order to be a direct quote (symbol references at runtime resolved to point to the memory address of a direct reference) system identification
5> Initialization: static part assigned to the initial value of an execution class initialization process <clinit> () methods, and examples of the method of initialization process init
6> Uninstall: System.exit (), normal termination, abnormal termination and error, the virtual machine process is terminated
2. Class loading
Java loading is done by the class loader, using the full classes with parents trust mechanism, the role of prevention of environmental contamination and malicious attacks, this is a one way to ensure the safety of the expense of efficiency, the class loader product .class objects, classes loaded not loaded at the first call to a class, but when it is expected to load a class that will be used, if LinkageError error, then very likely be incompatible reasons
3. The class loader
1> boot class loader Bootstrap ClassLoader: responsible for loading the JAVA_HOME \ lib directory, or through -Xbootclasspath specified path parameter, and is recognized (identified by file name, such as rt.jar) class, a virtual machine using c ++ , does not allow direct manipulation by reference
2> extension class loader Extension ClassLoader: responsible for loading the JAVA_HOME \ lib \ ext directory, the developers can add their own .jar file or library files to the extensions directory of classpath, so that it can
The extension class loader.
3> application class loader Application ClassLoader: the user is responsible for loading the library path, developers can be used directly extended standard class loader, class loader also be called a system, for example: from the class definition package;
4> custom class loader: Inheritance java.lang.ClassLoader way to achieve a custom class loader
Achieve order: custom class loader, loader application class, expand class loader, boot class loader.
5> thread context class loader: the default class loader for the application class loader, by Thread.currentThread () setContextClassLoader (ClassLoader) to set, each thread can be thread context class loader parent thread is set in advance. class loader. This is mainly used to break parent delegation model libraries allow the parent class loader class loader loads by sub needed
4. parents realize source delegation mechanism analysis
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException{
// synchronization lock to ensure thread safety
synchronized (getClassLoadingLock(name)) {
// first determine whether or not the type has been loaded, if not already loaded loaded
Class<?> c = findLoadedClass(name);
// if it is not loaded, delegate to the parent class loader or delegated to start classes loaded
if (c == null) {
long t0 = System.nanoTime();
try {
// If the parent class loader exists, it delegated to the parent class loader loads
if (parent != null) {
c = parent.loadClass(name, false);
} else {
// If the parent class loader does not exist, check whether it is loaded by the boot class loader
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
}
if (c == null) {
// If the parent class loader and class loader will start loading the task can not be completed before loading function calls itself
long t1 = System.nanoTime();
// findClass method can be overridden
c = findClass(name);
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
5.Java class loading process
When the class received a class loader to load task, it will give its parent class loader, and only when the parent class loader was unable to finish loading tasks (can not find the corresponding class in the region identified), only to load their own, the two classes equal jvm if desired, then it will need a class loader to load the same, which is a prerequisite, different classes loaded classes are not equal, even if the load is the same class in different classloader It is not equal.
6. initialization
6.1 initialization class
<Clinit> () method to give all class member variables compiler automatically collected class of statements into assignment operation and the static block of statements (static {} block) is generated by the compiler combined sequence is a statement in the source files appear in the order determined.
<Clinit> () constructor method with a different class, it does not need to explicitly call the parent class constructor, the virtual guaranteed subclass <clinit> () method prior to performing, parent class <clinit> () method It has been implemented, so the first execution in the virtual machine class <clinit> () method must be java.lang.Object. It still means that a block of statements as defined in the parent class takes precedence over variable subclass assignment. <Clinit> () method for the class or interface is not essential, if a class is not a static block of statements nor the variable assignment, then the compiler can not generate this class <clinit> () method. The interface may be a variable assignment, so the interface is also generated <clinit> () method. However, various interfaces and classes that implements the interface <clinit> () method does not need to run a parent interface <clinit> () method. Only when the parent variables defined in the interface is used, the parent interface will be initialized section is called. Further, the interface implementation class initialization will not be performed when interface <clinit> () method, will be added at compile time constants constant pool, without direct reference to the definition of the constants based essentially transformed into the constant pool itself references, so do not trigger initialization constants defined in the class, the virtual guarantee of a class <clinit> () method is properly locked and synchronized in a multithreaded environment. If there are multiple threads at the same time to initialize a class, then there will only be one thread to perform this type of <clinit> () method, other threads are blocked need to wait until the active thread execution <clinit> () method is completed. If you have a long time-consuming operation in a class of <clinit> () method, then it may cause more than one process blocked.
6.2 Examples initialization inlet (bottom loaded class class)
Calls, new, reflection, part of the main static method, after reading believe <clinit> () method has a certain understanding of the execution order on a static block of code, such as uninitialized initialized subclasses, and not in the sub- static part of the parent class's static methods class called, then the parent class loader is the class of the lowest class (top-level class is the Object class), etc.
6.3 instance initialization
<Init> method: initialize instance implemented in the example of the reflection to be initialized, and so new new
7 Example:
1. See analysis of java basic program, in conjunction with the above-described reasonable explanation of the basic procedure of Example Analysis java
2. The class loader
public class ValidateClassLoader { public static void main(String[] args) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); System.out.println(loader); System.out.println(loader.getParent()); System.out.println(loader.getParent().getParent()); } }// sun.misc.Launcher$AppClassLoader@6d06d69c //sun.misc.Launcher$ExtClassLoader@70dea4e
// null
Reason: The reasons null, because the Bootstrap Loader (boot class loader) is implemented in C language, corresponding to the object can not be found in the jvm identified;
3. custom class loader
package com.xrq.classloader; public class Perso{ private String name; public Person(){ } public Person(String name){ this.name = name; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String toString(){ return " " + name; } } public class MyClassLoader extends ClassLoader{ private String root; public String getRoot() { return root;
} public void setRoot(String root) { this.root = root; } protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = getClassBytes(name); Class<?> c = this.defineClass(name, bytes, 0, bytes.length); return c; } catch (Exception e) { e.printStackTrace(); } return super.findClass(name); } private byte[] getClassBytes(String name) throws Exception{ try { String fileName = root + File.separatorChar + name.replace('.', File.separatorChar) + ".class"; InputStream ins = new FileInputStream(fileName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = 0; while ((length = ins.read(buffer)) != -1) { baos.write(buffer, 0, length); } return baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null;} public static void main(String[] args) throws Exception { MyClassLoader classloader = new MyClassLoader(); classloader.setRoot=”E:”; Class<?> c1 = Class.forName("com.Person", true, classloader); Object obj = c1.newInstance(); System.out.println(obj.getClass().getClassLoader()); } }
/ * This is actually added stream file bytes, then call Class c = this.defineClass (name, bytes, 0, bytes.length) generating a class object <?>; Return c; and returning * /
/ * Output is perhaps the application class loader, it is because there is no mechanism to undermine parental trust, have the relevant class loader object has been loaded, you can clear the cache after you remove in memory, or when the rewrite loadclass undermine parental trust mechanism * /
Description: Parents do not want to break the delegate only need to rewrite findClass method can, if you need to break can be achieved by overriding loadClass method
Note: Here, the address needs to be transmitted in a manner fully qualified name of the custom class loader Used relatively small, and a custom class loader in some cases (ways to achieve rewriting loadclass) destroys parent delegation mechanism