search
HomeJavajavaTutorialDetailed explanation of JAVA class loading mechanism (recommended)

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”);

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

Test.doSomething();

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;

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);
 }
}

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];
 }
}

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);
 }
}

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
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.