search
HomeJavajavaTutorialDetailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

In the previous article, we explained Class files. In this article, we will talk about how the virtual machine loads these Class files? What happens to the information in the Class file after it enters the virtual machine? This involves the class loading mechanism.

The class loading mechanism is to load the class data from the Class file into the memory, verify the data, convert, parse and initialize it, and finally form a java type that can be directly used by the virtual machine. This series of processes are completed during the running of the program.

Class loader

The class loader is the part in the red box in the figure below. It obtains the binary bytes describing this class through the fully qualified name of a class. Stream, thereby dynamically loading java classes into the memory space of the JVM.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Applicable scenarios

For the loading phase of a non-array class, you can use the system This can be done by the provided boot class loader, or it can be done by a user-defined class loader.
For the array class, it is created directly by the java virtual machine without going through the class loader.

Parental delegation mechanism

Parental delegation mechanism is a method used by class loading. If a class loader receives a class loading request, it will not try to load the class itself first, but delegates the request to the parent class loader to complete. This is true for every level of class loader. Only when the parent loader reports that it cannot complete the request, the child loader will try to load it by itself.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Analogy to reality: Xiao Ming wants to buy a toy excavator, but he is too embarrassed to say it directly. So, the following conversation took place.

Xiao Ming asked his father: Dad, do you have an excavator?
Dad said: No
Then Dad asked Grandpa: Dad, Dad, do you have an excavator?
Grandpa said: No
Then Grandpa asked Great Grandpa: Dad, Dad, do you have an excavator?
Grandpa said: Me neither. Let your great-grandson buy one.
As a result, Xiao Ming happily bought a toy excavator by himself.

Category

The startup class loader is implemented in C and is part of the virtual machine itself.
Other class loaders are implemented in the Java language, independent of the virtual machine, and all inherit from the abstract class java.lang.ClassLoader.

Benefits

Take the String class as an example. Even if the user writes an implementation of the String class himself, when loading this class, it will only be delegated to the startup class loader to load the original String class in the JDK, and the custom String class will never be loaded. transfer. This ensures the security of the system.

When is class loading performed?

There are and only the following 5 ways to load a class immediately

(1) When using new to instantiate an object; reading or configuring the static fields of a class (modified by final, already being compiled) (except when the result is put into the static field of the constant pool); when calling a static method of a class.

(2) When using the method of the java.lang.reflect package to make a reflective call to the class. If the class has not been initialized, its initialization needs to be triggered first.

(3) When initializing a class, if it is found that its parent class has not been initialized, you need to trigger the initialization of its parent class first.

(4) When the virtual machine starts, the user needs to specify a main class to be executed (the class containing the main() method), and the virtual machine will first initialize the main class

Detailed description of the class loading process

The class loading process is divided into 5 steps. Most of them are dominated and controlled by the virtual machine, except for the following two situations:

In the loading phase

Developers can participate through a custom class loader

In The initialization phase

will execute the developer's code to initialize class variables and other resources

1. Loading

Things that the virtual machine needs to complete:
(1) Obtain the binary byte stream that defines this class through the fully qualified name of a class.
(2) Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.
(3) Generate a java.lang.Class object representing this class in memory as an access entry for various data of this class in the method area.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

2. Verification

The purpose of verification is to ensure that the Class file The information contained in the byte stream meets the requirements of the current virtual machine and will not endanger the security of the virtual machine itself.
It is divided into 4 steps: file format verification, metadata verification, bytecode verification, and symbol reference verification. Among them, file format verification operates directly on the byte stream, and the remaining three items are performed in the method area.

3. Preparation

This stage is the stage to formally allocate memory for class variables and set the initial value of class variables. It is allocated in the method area. There are two points to note:

(1) At this time, only memory allocation is performed for class variables (variables modified by static), not object variables. Memory is allocated to an object when the object is instantiated and is allocated to the Java heap along with the object.

(2) If a class variable is not final modified, its initial value is the zero value of the data type. For example, the int type is 0, and the boolean type is false. Give an example to illustrate:

public static int value=123;

The initial value after the preparation phase is 0 instead of 123, because no java method has been executed at this time, and the putstatic instruction that assigns the value to 123 is after the program is compiled. , stored in the class constructor () method. Therefore, the action of assigning value to 123 will only be executed during the initialization phase.

public static final int value=123;

Because there is final at this time, the value has been assigned to 123 during the preparation stage.

4. Parsing

The parsing phase is the process in which the virtual machine replaces the symbol references in the constant pool with direct references. Classes or interfaces, fields, class methods, interface methods, etc. can be parsed.

What is a symbolic reference:

A symbolic reference is a string containing class information, method name, method parameters and other information. It is used in the method table of the class for actual use. Find the corresponding method.

What is a direct reference:

The direct reference is the offset, which can be found directly in the memory area of ​​the class The starting position of the method bytecode. The
symbol reference tells you some characteristics of this method. You need to use these characteristics to find the corresponding method. Direct quotation means directly telling you where this method is.

5. Initialization

This stage is used to initialize class variables and other resources. It is the execution class constructor() The method process is when the Java program code defined in the class actually begins to be executed.

The above is a detailed explanation of the JAVA virtual machine class loading mechanism. For more related questions, please visit the PHP Chinese website: JAVA Video Tutorial

The above is the detailed content of Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
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 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 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...

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...

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...

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 set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools