Home Java javaTutorial Detailed explanation of JAVA class loading mechanism (recommended)

Detailed explanation of JAVA class loading mechanism (recommended)

Dec 14, 2016 pm 05:30 PM

JAVA source code compilation consists of three processes:

1. Source code compilation mechanism.

2. Class loading mechanism

3. Class execution mechanism

Here we mainly introduce the two mechanisms of compilation and class loading.

1. Source code compilation

Code compilation is completed by the JAVA source code compiler. The main purpose is to compile the source code into a bytecode file (class file). The bytecode file format is mainly divided into two parts: constant pool and method bytecode.

2. Class loading

The life cycle of a class starts from being loaded into the virtual machine memory and ends when it is unloaded from the memory. There are seven stages in the process, of which the part before initialization is the part of class loading

Loading----verification----preparation----parsing-----initialization----use--- --Uninstall

The system may load a certain class when it is used for the first time, or it may use a preloading mechanism to load a certain class. When a certain java program is run, a java virtual machine process will be started, twice The running Java program is in two different JVM processes, and no data is shared between the two JVMs.

1. Loading phase

Loading in this process is a stage in the class loading mechanism. Do not confuse these two concepts. The things that need to be completed at this stage are:

1) Obtain through the fully qualified name of a class Defines a binary byte stream for this class.

2) Convert the static storage structure represented by this byte stream into a runtime data structure in the method area.

3) Generate a Class object representing this class in the java heap as the entrance to access the data in the method area.

Since the first point does not specify where and how to obtain the binary byte stream of the class, this area leaves a lot of room for my developers to play. I will introduce this later in the class loader.

2. Preparation phase

This phase officially allocates memory for class variables (variables modified by static) and sets the initial value of the class variable. This memory allocation occurs in the method area.

1. Note that there is no memory allocation for instance variables. Instance variables will be allocated in the JAVA heap along with the object when the object is instantiated.

2. The initial value set here usually refers to the zero value of the data type.

private static int a = 3;
The value of variable a of this class is 0 after the preparation phase. The assignment of 3 to variable a occurs in the initialization phase.

3. Initialization phase

Initialization is the last step of the class loading mechanism. At this time, the execution of the JAVA program code defined in the class actually begins. In the previous preparation stage, the class variables have been assigned the initial values ​​required by the system. The most important thing in the initialization stage is to initialize the class variables. The focus is on the order of initialization of various resources between parent and child classes.

There are two ways to specify initial values ​​for class variables in Java classes: 1. Specify initial values ​​when declaring class variables; 2. Use static initialization blocks to specify initial values ​​for class variables.

Timing of initialization

1) When creating a class instance, the following are: 1. Use the new keyword to create an instance; 2. Create an instance through reflection; 3. Create an instance through deserialization.

new Test();
Class.forName(“com.mengdd.Test”);
Copy after login

2) Call the class method (static method) of a certain class

Test.doSomething();
Copy after login

3) Access the class variable of a certain class or interface, or assign a value to the variable of this class.

int b=Test.a;
Test.a=b;
Copy after login

4) Initialize a subclass of a certain class. When a subclass is initialized, all parent classes of the subclass will be initialized.

5) Directly use the java.exe command to run a main class.

Except for the above methods that will automatically initialize a class, other methods of accessing a class will not trigger the initialization of the class and are called passive references.

1. Subclasses refer to static variables of the parent class, which will not cause the subclass to be initialized.

public class SupClass
{
 public static int a = 123;
 static
 {
  System.out.println("supclass init");
 }
}
public class SubClass extends SupClass
{
 static
 {
  System.out.println("subclass init");
 }
}
public class Test
{
 public static void main(String[] args)
 {
  System.out.println(SubClass.a);
 }
}
Copy after login

Execution result:

supclass init
123

2. Defining a reference class through an array will not trigger the initialization of this class

public class SupClass
{
 public static int a = 123;
 static
 {
  System.out.println("supclass init");
 }
}
public class Test
{
 public static void main(String[] args)
 {
  SupClass[] spc = new SupClass[10];
 }
}
Copy after login

Execution result:

3. When referencing a constant, it will not Trigger the initialization of this class

public class ConstClass
{
 public static final String A= "MIGU";
 static
 {
  System.out.println("ConstCLass init");
 }
}
public class TestMain
{
 public static void main(String[] args)
 {
  System.out.println(ConstClass.A);
 }
}
Copy after login

Execution result:

MIGU

When a class variable is modified with final, its value has already been determined and put into the constant pool at compile time, so when accessing this class variable When, it is equal to getting it directly from the constant pool and not initializing the class.

Steps of initialization

1. If the class has not been loaded and connected, the program will first load the class and connect.

2. If the direct parent class of this class is not loaded, initialize its direct parent class first.

3. If there are initialization statements in the class, the system executes these initialization statements in sequence.

In the second step, if the direct parent class has another direct parent class, the system will repeat these three steps again to initialize the parent class, and so on. The first thing the JVM initializes is always the java.lang.Object class. . When a program actively uses any class, the system will ensure that the class and all parent classes will be initialized.

The above is the JAVA class loading mechanism (recommended) introduced by the editor. I hope it will be helpful to everyone. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)! !


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles