Java Series notes (1)-Java class loading and initialization

Source: Internet
Author: User

Directory

    1. Class Loader
    2. Dynamic loading
    3. Link
    4. Initialization
    5. Example

Class Loader

Before you understand the mechanics of Java, you need to understand how the class is loaded in the JVM (the Java Virtual machine), which is important for understanding the other Java mechanisms later.

Each class is compiled with a class object stored in the. class file, and the JVM uses the ClassLoader (class Loader) to load the class's bytecode file (. Class), the ClassLoader is essentially a class loader chain, in general, we only use a native ClassLoader, which only loads trusted classes such as the Java API, usually just loaded on a local disk, and these classes are generally enough for us to use. If we need to download the. Class bytecode file from a remote network or database, then we need to mount the extra ClassLoader.

In general, the ClassLoader is organized in a tree-like hierarchy, with each loader having a parent classloader. In addition, each ClassLoader supports proxy mode, that is, the loading of Java classes can be done by itself, or it can be proxied to other ClassLoader.

There are two kinds of loading order of class loaders, one is the parent class first policy, one is its own priority policy, the parent class precedence policy is a more general case (as the JDK adopts this method), under this strategy, the class will try to delegate to its parent class loader before loading a Java class, only if the parent class loader cannot find it. , just try to load it yourself. The preferred strategy is in contrast to the parent class, which first tries the sub-economic loading, which is not found until the parent ClassLoader is loaded, which is common in web containers such as Tomcat.

Dynamic loading

Regardless of the class loader used, the class is dynamically loaded into the JVM the first time it is used. This sentence has two meanings:

    1. The Java program is not necessarily fully loaded at run time, only to find the class's. class file locally or remotely, and to verify and load it, only if the class has not yet been loaded.
    2. The class is loaded when the program creates the first reference to a static member of a class, such as a static variable for a class, a static method, and a construction method-the constructor method is also static. This feature of Java is called: dynamic loading .

It is necessary to differentiate between loading and initialization, loading a class of. class files that do not assume that the class object is initialized, and, in fact, the initialization of one of the classes consists of 3 steps:

    • Load (Loading), performed by the ClassLoader, finds bytecode, and creates a class object (created only);
    • Link (linking), verify the bytecode, allocate storage space for the static domain (just allocate, do not initialize the storage space), parse the class to create the application required for other classes;
    • Initialize (initialization), first execute static initialization block static{}, initialize static variables, and execute static methods (such as construction methods).

Link

After the class is loaded, Java needs to link the steps, which simply means that the loaded Java binaries are combined into the JVM's running state. It consists of 3 steps:

    1. Verification (verification), verification is to ensure that the binary bytecode in the structure of correctness, specifically, the work includes detection type correctness, access property correctness (public, private), check that the final class is not inherited, check the correctness of static variables and so on.
    2. Preparation (preparation), the preparation phase is mainly to create a static domain, allocate space, to set default values for these fields, note that there are two points: one is in the preparation phase will not execute any code, just set the default value, two are these default values are allocated, the native type is all set to 0, such as: float : 0f,int 0, Long 0L, boolean:0 (Boolean type is also 0), other reference type is null.
    3. Parsing (Resolution), the process of parsing is to parse and locate the symbolic references of the interfaces, classes, methods, and variables in the class, parsing them into direct references (the symbolic reference is that the encoding is the location of a variable and an interface by a string, and the direct reference is the address translated by the symbol reference). and ensure that these classes are found correctly. The parsing process can cause other classes to be loaded. It is important to note that, depending on the parsing strategy, this step is not necessarily necessary, and some parsing strategies recursively parse all references at parse time, which is early resolution, which requires all references to exist, and one strategy is late resolution, which is also Oracle JDK's strategy, that is, when the class is only referenced, not really used, and does not parse, only to load and parse the class if it is actually used.

Initialization

Note: In the Java programming idea, the static{} clause is executed at the first load of the class and executed once (perhaps with a clerical error or translation errors, because the example of this book shows that Static was performed on the first initialization), and the Java depth adventure says static{} is executed at the first instantiation and executed once, both of which should be wrong, static{} is executed at the first initialization and executed only once; it can be judged by the following code:

Package myblog.classloader;/** * @project MyBlog * @create June 18, 2013 PM 7:00:45 * @version 1.0.0 * @author Zhangguang */public CLA SS Toy {        private String name;        public static final int price=10;                static {                System.out.println ("Initializing");        }        Toy () {                System.out.println ("Building");        }        Toy (String name) {                this.setname (name);        }        public static string Playtoy (string player) {                string msg = buildmsg (player);                SYSTEM.OUT.PRINTLN (msg);                return msg;        }        private string Buildmsg (string player) {                string msg = player + "plays" + name;                return msg;}        }  For the above class, execute the following code:  Class C = Class.forName ("Myblog.rtti.Toy");  C.newinstance ();

As you can see, the static{} clause is still executed when the forname initialization is performed without instantiation, but the constructor method is not executed, so the output is only initializing and there is no building.

With regard to initialization, @ Achun Axiao gives a very detailed scenario in the comments in this article, thanks @ Achun Axiao:

According to the Java Virtual Machine specification, all Java Virtual machine implementations must be initialized when each class or interface is first actively used by a Java program.

Active use has the following 6 types:
1) Create an instance of the class
2) Access a static variable of a class or interface, or assign a value to the static variable (a constant that can be determined at compile time) does not cause initialization of the class
3) Calling the static method of the class
4) Reflection (Class.forName (XXX.XXX.XXX))
5) Initializes a subclass of a class (equivalent to the active use of the parent class), but refers to the parent class element directly through the subclass, without causing the initialization of the subclass (see Example 6)
6) The Java Virtual machine is marked as the class of the startup class (containing the Main method)

Classes differ from the initialization of an interface, if a class is initialized, its parent or parent interface is also initialized, but if an interface is initialized, it does not cause the initialization of its parent interface.

Example

1, through the above explanation, will be able to understand the following program (the following part of the program from the Java Programming idea):

Class Toy {        static {                System.out.println ("Initializing");//static clause that executes only once when the class is loaded and initialized for the first time, and only once        }        Toy () {                System.out.println ("Building");//construction method, loaded each time a new object is declared        }}

For the above program segment, the first call to Class.forName ("Toy") executes the static clause, and if you execute new Toy () after that, only the construction method is executed.

2, you need to pay attention to newinstance () method

Class cc = Class.forName ("Toy");//Get Class (note that you need to use the fully qualified name with the package name) Toy toy= (Toy) cc.newinstance (); Equivalent to a new object, but the gum class must have a default constructor method (no parameter)

3, use literal constants . Class and Class.forName can all create applications to classes, but the difference is that when you create an app with a class object with Gum.class, it is not automatically initialized The class object (the static clause does not execute)

public class Testtoy {public        static void Main (string[] args) {                //try {                //Class C = Class.forName ("myblog.cl Assloader. Toy ");                } catch (ClassNotFoundException e) {                //E.printstacktrace ();                }                Class c = toy.class;//will not output any value        }}

The use of Toy.class is performed at compile time, so you must have the Toy. Class file in the compilation, or the compilation will fail, unlike Class.forName ("Myblog.classloader.Toy"), which is dynamically loaded at run time.

However, if the main method is written directly in the toy class, then calling Toy.class will cause initialization and output initializing, which is not caused by toy.class, but instead contains the startup method main, which causes the toy to initialize.

4, compile the constant amount . Back to the full class Toy, if the direct output: System.out.println (Toy.price), you will find that the static clause and the constructor method are not executed, because in Toy, the constant price is static final qualification, such constants are called compile -time constants, for which the constant is not initialized to be read.
Compile-time constants must meet 3 conditions: Static, Final, constant.

The following are not compile-time constants, and their application will cause initialization of the class:

static int a;final  int b;static final  int c= ClassInitialization.rand.nextInt (); static final  int D; static {    d=5;}

5,the nature of the static block . Note the following code:

Class Staticblock {        static final int c = 3;        static final int D;        static int e = 5;        static {                d = 5;                e = ten;                System.out.println ("Initializing");        }        Staticblock () {                System.out.println ("Building");}        } public class Staticblocktest {public        static void Main (string[] args) {                System.out.println (STATICBLOCK.C); C13/>system.out.println (STATICBLOCK.D);                System.out.println (STATICBLOCK.E);        }}

What is the output of this piece of code? Initialing output before C, D, E, or after? is the output of e 5 or 10?

execution, the result is:

3
Initializing
5
10

The answer is 3 first output, intializing then output, e output is 10, why?

The reason is this: when output C, because C is a compile constant, does not cause class initialization, so the direct output, output D, D is not a compile constant, so it will cause the initialization operation, that is, the execution of the static block, so D is assigned to 5,e is assigned to 10, and then output initializing, Output d is then 5,e to 10.

But why is E 10? Originally, the JDK automatically creates a static block for the initialization of E (ref.: http://www.java3z.com/cwbwebhome/article/article8/81101.html?id=2497), So the above code is equivalent to:

Class Staticblock {        static final int D;        static int e;                static {           e=5;         }        static {            d = 5;            e = ten;            System.out.println ("Initializing");        }        Staticblock () {            System.out.println ("Building");}        }    

Visible, executed sequentially , E is first initialized to 5, and then initialized to 10, so output 10.

Similarly, it is easy to think of the following code:

Class Staticblock {        static {                d = 5;                e = ten;                System.out.println ("Initializing");        }        static final int D;        static int e = 5;        Staticblock () {                System.out.println ("Building");}        }

In this code, the declaration of E is placed behind the static block, so that E is initialized to 10 and then initialized to 5, so that the code in E is output to 5.

6, when accessing the static domain of a Java class or interface, only the class or interface that really declares the domain is initialized (Java deep Adventure)

/** * Example from "Java Deep Adventures" chapter II * @author Zhangguang * */class B {        static int value =;        static {                System.out.println ("Class B is initialized");//output        }}class A extends B {        static {                System.out.println ("Class A is initialized"); Do not output        }}public class Superclasstest {public        static void Main (string[] args) {                System.out.println ( A.value);//Output:}        }

In this example, although value is referenced by a, but value is declared in the parent class B, only B is initialized, not the initialization of a.

Description

In the development process, I found that the foundation is too weak, reading in addition to the system to learn the basic syntax and usage of Java, a little bit of simple data structure and design patterns, no deep system of learning, and the work of the study is also East Akira a gun west, not solid and system. Think of a learning method: learned things can be expressed in a systematic manner, only to show that you have learned , so the author decided to learn to write, will learn the things in the form of blog expression.

This document will be continuously updated due to in-depth or erroneous revisions of the study.

"Java series of Notes" Is my Java application and learning process of notes, according to the Knowledge points Sub-chapters, write this series of notes is the purpose of learning , because the author is the side of the study, the level is limited, there must be omissions in the text, welcome treatise.

There are many references to older books and blogs, in principle will not be quoted in the original, but to join their own understanding of the transformation, if there are references, will be noted, if in doubt, please contact: [Email protected]

Update record

June 25, 2013: Published;

June 26, 2013: added @ Achun Axiao Comment: 6 scenarios that cause initialization;

June 28, 2013: Join the link and initialize the content, add example 6

References in this section

Java programming ideas, 14th Chapter

Java Deep Adventures

The nature of static blocks in Java: http://www.java3z.com/cwbwebhome/article/article8/81101.html?id=2497

Java class mount (Loading), link (linking), and initialize (initialization): http://blog.csdn.net/biaobiaoqi/article/details/6909141

Java Series notes (1)-Java class loading and initialization

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.