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

What is the class loader of Java virtual machine and the process of class loading

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

Share

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

Today Xiaobian to share with you about the Java virtual machine class loader and class loading process is what the relevant knowledge, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.

1. Overview of Class loading Subsystem 1.1

The class loading subsystem is responsible for loading Class files from the file system or network. The Class file has a specific file identity at the beginning of the file.

ClassLoader is only responsible for loading the class file, and it is up to Execution Engine to decide whether it can be run or not

The loaded class information is stored in a memory space called the method area. In addition to the class information, the method area also stores runtime constant pool information, which may also include string literals and numeric constants (this constant information is the memory mapping of the constant pool part of the Class file).

The constant pool in bytecode is loaded into the method area-> runtime pool information

1.2 class loader

Class file (bytecode file) exists on the local disk (hard disk). When the bytecode file is executed, it needs to be loaded into the method area of JVM, and then instantiate n identical instances according to the class object in the method area.

The Class file is loaded into the JVM, called the DNA metadata template, and placed in the method area.

In the Class file-- > JVM-- > eventually becomes a metadata template, and this process requires a transport (classloader Class Loader) to play the role of a courier.

two。 The loading process of the class 2.1.The loading process of the class is simplified 2.2 loading phase: Loading

Get the binary byte stream that defines this class through the fully qualified name of a class

Convert the static storage structure represented by this byte stream into the runtime data structure of the method area

Generate a java.lang.Class object representing this class in memory as an access entry for all kinds of data of this class in the method area

Small supplement: how to load bytecode files (.class)

The local system loads directly

Network acquisition: Web Applet

Jar, war package

Dynamic proxy: run-time calculation generation.

2.3 Link stage: Linking

Authentication (Verify)

The purpose is to ensure that the byte stream of the Class file contains information that meets the requirements of the current virtual machine, ensures the correctness of the loaded classes, and does not endanger the security of the virtual machine itself.

It mainly includes four kinds of verification: file format verification, metadata verification, bytecode verification, symbol reference verification.

Prepare (Prepare)

Allocate memory for the class variable and set the default initial value of the class variable, that is, zero value

(in the preparation phase a = 0, to the next stage (initialization phase) a = 1)

(the default values of variables are different for different data types, such as int = 0, reference type = null)

Static decorated with final is not included here, because final is assigned at compile time, and initialization is displayed in the preparation phase (the variable decorated by final is: constant)

Initialization is not assigned for instance variables, class variables are assigned in the method area, and instance variables are assigned to the Java heap along with the object

Parsing (Resolve)

The process of converting symbolic references within a constant pool to direct references

In fact, parsing operations are often accompanied by JVM after initialization.

Symbolic reference: a set of symbols to describe the referenced target. The literal form of symbolic references is clearly defined in the Class file format of the Java virtual machine specification

Direct reference: a pointer directly to the target, a relative offset, or a handle that indirectly locates to the target

Parsing actions are mainly aimed at classes or interfaces, fields, class methods, interface methods, method types, and so on. It corresponds to CONSTANT_Class_info, CONSTANT_Fieldref_info, CONSTANT_Methodref_info and so on in the constant pool.

2.4 initialization phase: initialization

The initialization phase is the process of executing the class constructor method clinit (), which does not need to be defined. The javac compiler automatically collects the assignment actions of all variables in the class and the statements in the static code block.

Example 1:

Public class Test {private static int astat2; private static int bread20; public static void main (String [] args) {System.out.println (a); System.out.println (b);}}

Example 2:

Public class Test {public static void main (String [] args) {System.out.println ("test");}}

Instructions in constructor methods are executed in the order in which statements appear in the source file

The clinit () method is different from the constructor of the class. (correlation: the constructor is an init from a virtual machine perspective ())

If the class has a parent class, JVM ensures that the clinit () of the parent class is completed before the clinit () execution of the subclass.

The virtual machine must ensure that the clinit () method of a class is locked synchronously under multithreading, and the virtual machine will only call the clinit method once, ensuring that the class is loaded only once.

3. Loaders for several classes

JVM supports two types of classloaders, bootstrap classloader (Bootstrap ClassLoader) and custom classloader (User-Defined ClassLoader).

Conceptually, a custom class loader generally refers to a class of class loaders customized by developers in a program, but the Java virtual machine specification does not define it that way. Instead, all class loaders derived from the abstract class ClassLoader are divided into custom class loaders (all but Bootstrap ClassLoader are custom class loaders).

Regardless of the classification of class loaders, there are always only three of our most common class loaders in programs

Code:

Public class Test {public static void main (String [] args) {ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader (); System.out.println (systemClassLoader); / / sun.misc.Launcher$AppClassLoader@18b4aac2: application classloader ClassLoader parent = systemClassLoader.getParent (); System.out.println (parent); / / sun.misc.Launcher$ExtClassLoader@34a245ab: extended classloader ClassLoader parent1 = parent.getParent (); System.out.println (parent1) / / null: bootstrap classloader: non-Java language implementation ClassLoader classLoader = Test.class.getClassLoader (); System.out.println (classLoader); / / sun.misc.Launcher$AppClassLoader@18b4aac2 ClassLoader classLoader1 = String.class.getClassLoader (); System.out.println (classLoader1); / / null}} 3.1 Boot classloader:

BootstrapClassLoader, a class loader, is implemented in the language Cpicard + and is nested within JVM.

It is used to load Java's core class libraries (content under the JAVA_HOME/jre/lib/rt.jar, resources.jar, or sun.boot.class.path path) and to provide classes needed by JVM itself.

Does not inherit from java.lang.ClassLoader and has no parent class loader

Load the extension class and application class loader and specify it as their parent class loader

For security reasons, the Bootstrap startup classloader only loads classes whose package names begin with java, javax, sun, etc.

3.2 extended class loader: ExtensionClassLoader

Written in Java, derived from the ClassLoader class

The parent class loader is: start the class loader

Load the class library from the directory specified by the java.ext.dirs system properties, or from the jre/lib/ extsubdirectory (extension directory) of the JDK installation directory. If the user-created jar package is placed in this directory, it will also be automatically loaded by the extension class loader.

3.3Application class loader: AppClassLoader

Written in java, derived from ClassLoader

The parent class loader is ExtensionClassLoader

Responsible for loading the class library under the path specified by the environment variable classpath or the system attribute java.class.path

This kind of loader is the default class loader in the program. Generally speaking, it loads all the classes applied by Java.

This kind of loader can be obtained through the ClassLoader # getSystemClassLoader () method

3.4 user-defined class loader

In the daily application development of Java, class loading is almost performed by the above three kinds of loaders. When necessary, we can also customize the class loader to customize the loading mode of the class.

Why use a custom classloader?

Isolated load class

Modify the way classes are loaded

Extended loading source

Prevent source code leakage

Implementation steps of user-defined class loader

By inheriting the abstract class java.lang.ClassLoader, we implement our own class loader to meet some special requirements.

Before JDK1.2, the ClassLoader class is always inherited and the loadClass () method is overridden to implement a custom class loader. But after JDK1.2, it is no longer recommended to override the loadClass () method. Instead, it is suggested that the custom class loading logic be written in the findClass () method.

If you don't have too complex requirements for class loaders, you can directly inherit the URLClassLoader class, so you can avoid writing the findClass () method and its way of getting byte code stream, and make the writing of custom class loaders more concise.

Inheritance system

Get ClassLoader

4. Parental appointment mechanism

The Java virtual machine loads class files on demand, that is, when you need to use this class, it loads its class file into memory to generate class objects. And when loading the class file of a class, the Java virtual machine adopts the parent delegation mode, that is, handing the request to the parent class, which is a task delegation mode.

If a class loader receives a request to load a class, it will not load it first, but delegate the request to the loader of the parent class to execute

If the parent class loader still has its parent class loader, it further delegates upward and recursively requests the startup class loader that will eventually reach the top level

If the class loader can complete the class loading task, it returns successfully. if the parent class loader cannot complete the loading task, the subclass loader will try to load it. This is the parent delegation mode.

advantage

Avoid repeated loading of classes

Protect program security, prevent core API from being tampered with at will: custom: java.lang.String.

Don't pick the name of the bag.

5. Other

There are two necessary conditions for indicating whether two class objects are the same class in JVM

The fully qualified class name of the class must be the same, including the package name

The ClassLoader (the ClassLoader instance object) that loads this class must be the same

Even if two classes come from the same file, but the class loader is not the same, the two class objects are not equal.

These are all the contents of the article "what is the class loader of the Java virtual machine and the process of class loading". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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