JVM class loading mechanism

Source: Internet
Author: User

1.class.forname ("Org.whatisjava.reflect.Foo") will first reflection. The Foo class is loaded into the JVM and returns the class object associated with it. The JVM initializes the Foo class after it has been loaded, invoking the code in its static block.

2. Class loading is the first step in a Java program, and studying the loading of classes can help you understand the JVM execution process and instruct developers to take more effective action in conjunction with program execution.

The second purpose of the research class loading mechanism is to enable the program to dynamically control class loading, such as thermal deployment, to improve the flexibility and adaptability of the program. , one, the simple process Java program run the place is memory, when executed at the command line: Java HelloWorld command, the JVM will load Helloworld.class into memory, and form 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. Three, class loader characteristics 1, when running a program, always by Appclass Loader (System class loader) Start loading the specified class. 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, and its parent loader is null.
Four, the class loader is easy to get, see the following example 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 ());
}
Printing results: Sun.mi[email protected]
[Email protected]
Null

Process finished with exit code 0 from the above results can be seen, and did not get to Extclassloader's parent Loader, because Bootstrap Loader (startup ClassLoader) is implemented in C language, Could not find a definite way to return the parent loader, so it returns NULL. There are three types of load class loading: 1, the command line starts the application by the JVM initialization load 2, through the Class.forName () method dynamic loading 3, through the Classloader.loadclass () method dynamic loading three way of difference is larger, Take a look at an example and get it: 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 a class without executing an 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 blocks when initialized
Class.forName ("Test2", false, loader);
}
} The same ClassLoader loaded class file 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). When the class file is loaded by the loader, a meta-information object describing the class structure is formed in the JVM, which can be used to learn the structure information of class, such as constructors, properties and methods, etc. Java allows the user to indirectly invoke the functionality of a class object by this class-related meta-information object.

2. Working mechanism

A class loader is a byte-code file that looks for a class and constructs an object component that the class represents within the JVM. In Java, the class loader loads a class into the JVM, taking the following steps:

(1) Loading: Find and import class files;

(2) Link: Merges the binary data of the class into the JRE;

(a) Verification: check the correctness of loading class file data;

(b) Preparation: Allocating storage space to static variables of the class;

(c) Parsing: Transferring symbolic references to direct references;

(3) Initialize: Static variable for class, static code block to initialize operation

Java programs can be dynamically extended by the runtime dynamic loading and dynamic link implementation, for example: If you write an application using an interface, you can wait until the runtime to specify its actual implementation (polymorphic), the parsing process can sometimes be executed after initialization, such as: Dynamic binding (polymorphic);

"Class initialization"

(1) When encountering the 4 bytecode directives of new, getstatic, putstatic, or invokestatic, if the class has not been initialized, it needs to trigger its initialization first. The most common Java code scenario for generating these 4 instructions is when instantiating an object with the new keyword, reading or setting the static field of a class (except for the static fields that were final decorated, which have been placed in the constant pool at compile time), and when invoking a static method of a class.

(2) When using the Java.lang.reflect package method to make a reflection call to a class, if the class has not been initialized, it needs to trigger its initialization first.

(3) When a class is initially initialized, it is necessary to trigger the initialization of its parent class if it finds that its parent class has not yet been initialized.

(4) When the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual opportunity initializes the main class first.

Only the above four situations trigger initialization, also known as an active reference to a class, except that all other methods do not trigger initialization, called a passive reference

Code Listing 1

Once the code is run, it will only output "---superclass init", not "subclass Init", and for static fields only classes that directly define the field will be initialized, so calling the static field of the parent class through the subclass will only trigger the initialization of the parent class. But this is to see different implementations of different virtual machines.

Each developer is certainly not unfamiliar with the Java.lang.ClassNotFoundExcetpion exception, which involves class loading in the Java technology architecture. Java's class loading mechanism is the core of the technical system, although not much directly with the majority of developers, but the mechanism behind it has a certain understanding to help troubleshoot the application of class loading failure and other technical issues, to understand the Java Virtual Machine Connection model and Java language Dynamics are very helpful.

With the above code analysis, we can have a more perceptual understanding of the Parental delegation class loading mechanism adopted by the JVM, and then we will analyze the relationship between the Startup class loader, the standard extension classloader, and the system ClassLoader. You may have seen a picture like this from a variety of sources:


Figure three-Class loader default delegation diagram

The image above gives a visual impression that the system loader's parent ClassLoader is the standard extension class loader, and the standard extension ClassLoader is the parent class loader that launches the ClassLoader

3 How Java programs are dynamically extended


The Java connectivity model allows the user to run the extended reference program, either by loading the class or interface known at compile time through the predefined loader in the current virtual machine, or by allowing the user to define the class loader to dynamically extend the user's program at run time. With a user-defined class loader, your program can load classes or interfaces that are not known or exist at compile time, and dynamically connect them and perform selective parsing.
There are two ways to dynamically extend a Java application at run time:

3.1 Call Java.lang.Class.forName (...) Load class

This method is actually discussed earlier in this paper, and in the answer to question 2, it is explained that the method call triggers which ClassLoader starts loading the task. What needs to be explained here is the multi-parameter version of the forname (...) Method:

[Java]View PlainCopy 
    1. Public static class<?> forname (String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException

The Initialize parameter here is very important. It indicates whether to complete initialization at the same time (note: The single-parameter version of the Forname method is initialized by default). Some scenarios require the initialize to be set to true to force the load to complete initialization at the same time. For example, the problem of using DriverManager for the JDBC driver class registration is typical. because the static initialization method for each JDBC driver class uses DriverManager to register the driver, it can be used by an application. This requires that the driver class must be initialized, not just loaded. A very common usage of class.forname is when the database driver is loaded. such as Class.forName ("Org.apache.derby.jdbc.EmbeddedDriver"). Newinstance () is used to load the Apache Derby database driver.

3.2 User-defined class loader

From the previous analysis, we can see that in addition to the local implementation of the most closely related to the Startup class loader, including the standard extension class loader and the system ClassLoader, all other class loaders can be treated as a custom class loader, the only difference is whether the virtual machine is used by default. The previous content has already introduced several important methods in the Java.lang.ClassLoader abstract class, here is a brief description of the general user custom class loader workflow bar (can be combined with the following questions to see):
1, first check whether the type of the request has been loaded into the namespace of this class loader, if it has been loaded, return directly; otherwise go to step 2;
2, the delegation class loading request to the parent class loader (more precisely should be the parents class loader, the real virtual machine in the various class loaders will eventually render the tree structure), if the parent class loader can complete, the parent class loader loaded class instance; otherwise go to step 3;
3, call the Findclass of this class loader (... ) method to attempt to get the corresponding bytecode, if obtained, then call DefineClass (...). Imports the type to the method area, or fails if no corresponding bytecode or other reason is obtained, returning an exception to LoadClass (...). ), LoadClass (... Instead of throwing an exception, terminate the loading process (note: There are more than one type of exception here).
Description: The custom class loader described here refers to the version of JDK 1.2, which does not overwrite the change Java.lang.loadClass (...). There are delegated logic in the case.

The whole process of loading a class is as follows:

Figure VI The process of customizing the class loader load class

JVM class loading mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.