Detailed explanation of converting to the static {} statement block in java, javastatic

Source: Internet
Author: User

Detailed explanation of converting to the static {} statement block in java, javastatic

Address: http://blog.csdn.net/lubiaopan/article/details/4802430 thanks to the original author!

 

 

Static {} (static block) is executed only once when the class is loaded. It is generally used to initialize static variables and call static methods, next we will discuss in detail the features and applications of this statement block.

 

1. During a program execution, the content in the static {} statement block is only executed once. See the following example:

Example 1

Class Test {public static int X = 100; public final static int Y; = 200 public Test () {System. out. println ("Test constructor execution");} static {System. out. println ("static statement block execution");} public static void display () {System. out. println ("static method executed");} public void display_1 () {System. out. println ("instance method executed") ;}} public class StaticBlockTest {public static void main (String args []) {try {Class. forName ("Test"); Class. forName ("Test");} catch (ClassNotFoundException e) {e. printStackTrace ();}}}

Result: although two classes are executed. forName ("Test") statement, but only one "static method executed" statement is output; in fact, the second Class. the forName () Statement is invalid because one class is loaded only once in the life cycle of the VM, And because static {} is executed along with the class loading, no matter how many new object instances you have, static {} is executed only once. --For more information about class loading, see the appendix in this article.

 

Ii. Timing of executing the static {} statement block (in fact, it is the time for class loading in the Appendix)

 

As mentioned above, static {} is executed when the class is loaded. We must accurately understand the meaning of class loading. The meaning is as follows:

1. When Class. forName () is used to display the loading, the example 1 above is shown;

2. when instantiating a class, for example, changing the content of the main () function to: Test t = new Test (); // the principle is the same as that of 1, are displayed to load this Class, the reader can verify Test t = new Test (); and Test t = (Test) Class. forName (). newInstance (); these two statements have the same effect.

3. When calling static methods of the class, for example, changing the content of the main () function to: Test. display ();

4. When calling static variables of the class, for example, changing the content of the main () function to: System. out. println (Test. X );

 

In general, there are four situations, but we need to pay special attention to two points:

1. When calling static constants of a class, the class will not be loaded, that is, the static {} statement block will not be executed. You can verify it yourself (Set main () change the function content to System. out. println (Test. y);), you will find that the program outputs only one 200; (this is the specification of the Java Virtual Machine. If the compiler can calculate the value of a constant for a static constant of the runtime class, the class will not be loaded; otherwise, the class will be loaded)

2. Use Class. in the forName () format, we can also set whether to load the Class, for example, set the Class. change forName ("Test") to Class. forName ("Test", false, StaticBlockTest. class. getClassLoader (), you will find that the program has no output, that is, Test is not loaded, and static {} is not executed.

 

Iii. execution sequence of the static {} statement Block

 

 

1,When there are multiple static {} in a class, it is executed in the previous and subsequent order defined by static;

2,The call statement is executed only after the content of the static {} block is executed;

Example 2

Public class TestStatic {
Static {
System. out. println (1 );
}
Static {
System. out. println (2 );
}
Static {
System. out. println (3 );
}
Public static void main (String args []) {
System. out. println (5 );
}
Static {
System. out. println (4 );
}
}
Result: The program will output 1, 2, 3, 4, 5

3. If a static variable is assigned an initial value (for example, static int X = 100) during definition, the value assignment operation is also completed during class loading, in addition, when a class contains both static {} and static variables, the principle of "first defining first execution" is also followed;

Example 3

Class Test {
Public static int X = 300;
Static {
System. out. println (X );
X = 200;
System. out. println (X );
}
}

Public class StaticBlockTest {
Public static void main (String args []) {
System. out. println (Test. X );
}
}

Result: The program will output 300,200,200 in sequence, and then execute the static {} statement block after running X = 300.

 

Iv. static {} statement block Application

 

1. Applications in JDBC

Readers familiar with JDBC should know that java has a DriverManager class for managing various database drivers and establishing new database connections. The DriverManager class contains some Drivers classes. These Drivers classes must register themselves by calling the DriverManager's registerDriver () method. When will the registration happen? The answer is as follows:

All Drivers classes must contain a static method. Using this static method, you can create an instance of this class and register it with the DriverManage class when loading the instance. We often use Class. forName () is used to load the driver. registration occurs during the execution of this statement. The static method of Drivers mentioned earlier is put in static, when the driver is loaded, the static {} will be executed to complete the registration.

 

2. Applications in hibernate

SessionFactory in hibernate is a heavyweight class. Creating an object instance of this class consumes a lot of system resources. If you create an instance of this class every time you need it, it will obviously reduce the program execution efficiency, therefore, we often put the class instantiation in a static {}, which only needs to be executed during the first call to improve the execution efficiency of the program, as shown below:

Static {
Try {
Configuration. configure (configFile );
SessionFactory = configuration. buildSessionFactory ();
} Catch (Exception e ){
System. err. println ("% Error Creating SessionFactory % ");
E. printStackTrace ();
}
}

 

V. Appendix

 

Class loading:The role of Java commands is to start the virtual machine. The virtual machine reads the content in the bytecode file (. class file) from the disk into the virtual machine through the input stream, and stores the content in the Process of class loading.

 

Class loading features:
*In the life cycle of a VM, a class is loaded only once.
*Class loading principle: delayed loading means less loading because the space of virtual machines is limited.
*Class loading time:
1) class to be loaded when an object is created for the first time.
2) classes must be loaded when static methods are called, and classes will be loaded when static properties are accessed.
3) When a subclass is loaded, the parent class must be loaded first.
4) Creating object references does not load classes.
5) when the subclass calls the static method of the parent class
(1) When the subclass does not cover the static method of the parent class, only the parent class is loaded, not the subclass.
(2) When a subclass has a static method that overwrites the parent class, it loads both the parent class and the Child class.
6) Access static constants. If the compiler can calculate the value of a constant, classes will not be loaded, for example, public static final int a = 123; otherwise, classes will be loaded, for example: public static final int a = math. PI.

Related Article

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.