Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the process of loading, verifying and preparing JDK15 classes

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to understand the JDK15 class loading, verification, preparation process", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand the JDK15 class loading, verification, and preparation process.

Preparation for using classes

Any program needs to be loaded into memory to communicate with CPU, and bytecode .class files are no exception, and classes can be instantiated only when loaded into memory.

The mission of ClassLoader is to load .class class files into memory in advance, using Parents Delegation Model (traceability delegation model) when loading classes.

Java's classloader is a runtime core infrastructure module that loads, links, and initializes classes at the beginning of startup:

Java class loading process

Load- loading

Executed by the class loader.

Read the class file (usually look in the path specified by classpath, but classpath is also not required), look for bytecode, resulting in a binary stream, and convert to a specific data structure.

Initially verify the cafe babe magic number, constant pool, file length, whether there is a parent class, etc., and then create a java.lang.Class instance of the corresponding class.

Link- link

Merges binary data from classes that have been read into memory into the JVM runtime environment.

It includes the following three steps:

Verification

Ensure the correctness of the loaded class. Verifying the bytecode in the class is a more detailed check, such as final compliance, correct type, and reasonable static variables.

Prepare for

Allocate memory for the static field of a class, set initial defaults, parse classes and methods to ensure the correctness of cross-references between classes, and complete the layout of memory structure.

Analysis

If necessary, parse all references to other classes created by this class, and convert the symbolic references of the constant pool to direct references.

Init- initialization

When the class constructor is executed, if the assignment is done through static methods of other classes, the alternative class is parsed immediately, and the assignment is performed through a return value after execution in the JVM stack.

Class loading is the process of instantiating a .class bytecode file into a Class object and initializing it.

During this process, JVM initializes all parent classes on the inheritance tree that have not yet been initialized, and executes all unexecuted static code blocks, static variable assignment statements, and so on.

When some classes are in use, they can also be loaded by the class loader on demand.

All lowercase class is the keyword used to define the class

And the uppercase Class, which is the class of all class

This sentence is difficult to understand. A class is already an abstraction of something in the real world. Why is this abstraction still an object of another class Class?

The sample code is as follows:

The first note:

NewInstance () under the Class class has been made obsolete in JDK9, using getDeclaredConstructor (). NewInstance ()

Highlight the difference between new and newInstance

New is strongly typed, and any constructor can be called. When using the new operation, this class can not be loaded.

However, the newInstance under the Class class is weakly typed and can only call the no-parameter constructor.

If there is no default constructor, an InstantiationException exception is thrown

If this constructor does not have permission to access, the invalid IllegalAccessException exception

Java decouples the implementation of the class from the definition of the class through the class loader, so it is the inevitable choice to realize interface-oriented programming and dependency inversion.

Note in place 2

Other declarations can be obtained in a similar way, such as annotations, methods, etc.

Note 3: can private members be modified outside the class?

With setccessible (true), you can use the set method of the Class class to modify its value

If there is no such step, the following exception is thrown:

1 location of loading

Loading is the first step in the Class Loading process.

1.1 loading process

JVM mainly does the following things:

Get the binary byte stream (class file) of the class through the fully qualified name of the class (guaranteed global uniqueness)

In the process of running the program, when you want to access a class, if you find that the class has not been loaded and meet the conditions for class initialization, you will find the binary byte stream of the class according to the fully qualified name of the class to be initialized, and start the loading process.

The advantage of giving the action of "getting the binary byte stream of the class through the fully qualified name of the class" in the class loading phase to the class loader outside the virtual machine is that you can implement the class loader to load classes in other formats. As long as it is a binary byte stream, this greatly enhances the flexibility of the loader.

Convert the static storage structure of this byte stream into the run-time data structure of the method area

Create a java.lang.Class object of this class in memory as the access entry for all kinds of data of the class in the method area, so all classes can call the getClass method

When the program is running, all access to the class is through this class object, that is, the Class object is the interface provided to the outside world to access the class.

1.2 load Source

The JVM specification gives greater leniency to the loading process. Generally, binary byte streams are read from compiled local class files, and can also be read from the following places

Zip package

Jar, War, Ear, etc.

Other file generation

The corresponding Class class is generated from the JSP file

In the database

The binary byte stream is stored in the database and then read from the database when loaded. Some middleware do this to enable code distribution between clusters

The network

Get binary byte streams from the network, such as Applet

Run-time dynamic computing generation

Dynamic proxy technology, using PRoxyGenerator.generateProxyClass to generate binary byte streams of proxy classes in the form "* $Proxy" for specific interfaces

1.3 the difference between class and array loading process

Arrays also have types, called "array types", such as:

String [] str = new String [10]

The array type of this array is Ljava.lang.String, and String is only the element type of this array.

When the program encounters the new keyword to create an array, JVM creates the array class directly, and then the class loader creates the element types in the array.

The loading of a normal class is created by the class loader. It can be done either by using the boot class loader provided by the system or by a user-defined class loader (that is, overriding the loadClass () method of a class loader)

1.4 points for attention in the loading process

The JVM specification does not provide a data structure for the class to store in the method area.

After the class is loaded, the binary byte stream is stored in the method area with a specific data structure, but the stored data structure is defined by the virtual machine itself and is not specified by the virtual machine specification

The JVM specification does not specify where Class objects are stored

After the binary byte stream is stored in the method area in a specific format, JVM creates an object of the java.lang.Class class as the external provider of the class

Since it is an object, it should be stored in the Java heap, but the JVM specification does not specify a limit. Different virtual machines store this object according to their own requirements.

HotSpot stores the Class object in the method area.

The loading phase and the linking phase are intersected

There is a strict limit on the start order of each step in the process of class loading, but there is no limit on the end order of each step. That is, the class loading process must begin in the following order:

Load-> Link-> initialize

But the end order doesn't matter, so because the processing time of each step is different, some steps will cross.

2 Verification

The validation phase is time-consuming and is very important but not necessarily necessary (because it has no effect on the run time of the program). If the code you are running has been used and verified repeatedly, you can turn it off using the-Xverify:none parameter to shorten the class loading time.

2.1 purpose of verification

Ensure that the information in the binary byte stream conforms to the virtual machine specification, and there is no security problem.

2.2 necessity of verification

Although the Java language is a secure language, it ensures that programmers cannot access memory beyond the boundaries of the array, avoid converting an object to any type, and avoid jumping to lines of code that do not exist. In other words, the security of the Java language is guaranteed by the compiler.

But we know that the compiler and the virtual machine are two separate things. The virtual machine only recognizes the binary byte stream, and it does not care where the binary byte stream comes from. Of course, if the compiler gives it to it, it is relatively safe. But if it is obtained from other sources, then there is no way to ensure that the binary byte stream is secure.

As can be seen from the above, the virtual machine specification does not limit the source of the binary byte stream. At the bytecode level, what the above Java code cannot do can be realized, at least semantically. In order to prevent security problems in the byte stream, it needs to be verified!

2.3 process of verification

File format verification

Verify that the byte stream conforms to the specification of Class file format and can be processed by the current virtual machine.

This verification phase is based on the binary byte stream and is allowed to be saved in the method area only if it passes the verification at this stage.

The next three verification phases are based on the storage structure of the method area and no longer operate the byte stream directly.

As you can see from the above, before the loading starts, the binary byte stream has not yet entered the method area, but after the loading is completed, the binary byte stream has been stored in the method area.

Before the file format verification, the binary byte stream has not yet entered the method area, and the file format verification has passed before entering the method area.

That is, the file format verification is started immediately after the loading starts. After the verification is passed at this stage, the binary byte stream is converted into a specific data structure and stored in the method area, and then the next stage of verification and Class object creation are started.

This process confirms that loading and verification are cross-over.

Metadata validation

The information described by bytecode is semantically analyzed to ensure that it conforms to the Java syntax specification.

Bytecode verification

The most complex stage of the verification process. In this stage, the semantic analysis of data flow and control flow (mainly method body) is carried out. Bytecode verification will check and analyze the methods of the class to ensure that the method being verified will not do anything harmful to the virtual machine at runtime. If the bytecode of a class does not pass the bytecode verification, there must be a problem, but if a method passes the verification, it does not mean that it is safe.

Symbol reference verification

When JVM converts a symbolic reference to a direct reference, the conversion occurs in the parsing phase, which matches and verifies the information outside the class itself to ensure that the parsing can be performed normally.

At this point, I believe you have a deeper understanding of "how to understand the JDK15 class loading, verification, and preparation process". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report