Class Loading process detailed process 1: Loading stage


1, Overview

2, Process 1: Loading stage

3, Summary

1, Overview

In Java, data types are divided into basic data types and reference data types. The basic data type is pre-defined by the virtual machine, and the reference data type needs to be loaded.

According to the Java virtual machine specification, from the class file to the class loaded into memory to the class unloaded out of memory, its whole life cycle includes the following seven stages:

Among them, the three parts of verification, preparation and parsing are collectively referred to as Linking.

From the use process of classes in the program:

Let's introduce the seven stages involved in the life cycle of the class mentioned earlier.

2, Process 1: Loading stage

(1) . loading completed operations

The so-called loading, in short, is to load the bytecode file of Java class into machine memory, and build the prototype of Java class - class template object in memory. The so-called class template object is actually a snapshot of the Java class in the JVM memory. The JVM stores the constant pool, class fields, class methods and other information parsed from the bytecode file into the class template, so that the JVM can obtain any information in the Java class through the class template at runtime, traverse the member variables of the Java class, and call Java methods.

The reflection mechanism is based on this foundation. If the JVM does not store the declaration information of Java classes, the JVM cannot reflect at run time.

In the loading phase, in short, find and load the binary data of the Class and generate an instance of the Class.

When loading classes, the Java virtual machine must complete the following three things:

  • Obtain the binary data stream of the class through the full name of the class;
  • The binary data stream of the parsing class is the data structure in the method area (Java class model);
  • Create Java An instance of lang. class class, which is used to represent this type and serves as an access entry for various data of this class in the method area;

(2) 2. Acquisition method of binary stream

For the binary data stream of class, virtual machine can generate or obtain it in many ways. (as long as the read bytecode conforms to the JVM specification):

  • The virtual machine may read a file through the file system class suffix files (most common);
  • Read jar, zip and other archive packages and extract class files;
  • Binary data of classes stored in the database in advance;
  • Use a protocol similar to HTTP to load through the network;
  • Generate binary information of a Class at runtime;

After getting the binary information of the class, the Java virtual machine will process the data and finally turn it into a Java An instance of lang.class. If the input data is not a ClassFile structure, a ClassFormatError will be thrown. (for example, if it doesn't start with cafebabe, ClassFormatError will be thrown).

(3) Location of Class model and Class instance

  • Location of class model

The class template is placed in the method area, jdk1 8 was in the permanent generation; JDK1.8 and then in meta space.

  • Location of Class instance

Class will After the class file is loaded into the meta space, a Java. Class file is created in the heap Lang. class object is used to encapsulate the data structure of the class in the method area. The class object is created during class loading, and each class corresponds to an object of class type.

As shown in the figure above, the external can obtain the Class data structure of Order by accessing the Class object representing the Order Class.

  • Explain again

The construction method of class is private, and only JVM can create it. java.lang.Class instance is not only an interface to access type metadata, but also a key data and entry to realize reflection. Through the interface provided by class, you can obtain the information associated with the target class Class file: method, field and other information.

Next, let's take a look at an example of accessing methods, fields and other information of the corresponding type through Class objects:

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

 * @Description: Process 1: loading phase
 * @Date: 2021/8/28 14:51
 * Through the Class class, Java All method information of lang.string Class, and print method access identifier and descriptor
public class LoadingTest {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("java.lang.String");
            //Gets all the methods declared by the current runtime class
            Method[] ms = clazz.getDeclaredMethods();
            for (Method m : ms) {
                //Gets the modifier of the method
                String mod = Modifier.toString(m.getModifiers());
                System.out.print(mod + " ");
                //Gets the return value type of the method
                String returnType = m.getReturnType().getSimpleName();
                System.out.print(returnType + " ");
                //Get method name
                System.out.print(m.getName() + "(");
                //Gets the parameter list of the method
                Class<?>[] ps = m.getParameterTypes();
                if (ps.length == 0) System.out.print(')');
                for (int i = 0; i < ps.length; i++) {
                    char end = (i == ps.length - 1) ? ')' : ',';
                    //Gets the type of the parameter
                    System.out.print(ps[i].getSimpleName() + end);
        } catch (ClassNotFoundException e) {


The operation results are as follows:

public boolean equals(Object)
public String toString()
public int hashCode()
public int compareTo(String)
public volatile int compareTo(Object)
public int indexOf(String,int)
public int indexOf(String)
public int indexOf(int,int)
public int indexOf(int)
static int indexOf(char[],int,int,char[],int,int,int)
static int indexOf(char[],int,int,String,int)
public static String valueOf(int)
public static String valueOf(long)
public static String valueOf(float)
public static String valueOf(boolean)
public static String valueOf(char[])
public static String valueOf(char[],int,int)
public static String valueOf(Object)
public static String valueOf(char)
public static String valueOf(double)
public char charAt(int)
private static void checkBounds(byte[],int,int)
public int codePointAt(int)
public int codePointBefore(int)
public int codePointCount(int,int)
public int compareToIgnoreCase(String)
public String concat(String)
public boolean contains(CharSequence)
public boolean contentEquals(CharSequence)
public boolean contentEquals(StringBuffer)
public static String copyValueOf(char[])
public static String copyValueOf(char[],int,int)
public boolean endsWith(String)
public boolean equalsIgnoreCase(String)
public static transient String format(Locale,String,Object[])
public static transient String format(String,Object[])
public void getBytes(int,int,byte[],int)
public byte[] getBytes(Charset)
public byte[] getBytes(String)
public byte[] getBytes()
public void getChars(int,int,char[],int)
 void getChars(char[],int)
private int indexOfSupplementary(int,int)
public native String intern()
public boolean isEmpty()
public static transient String join(CharSequence,CharSequence[])
public static String join(CharSequence,Iterable)
public int lastIndexOf(int)
public int lastIndexOf(String)
static int lastIndexOf(char[],int,int,String,int)
public int lastIndexOf(String,int)
public int lastIndexOf(int,int)
static int lastIndexOf(char[],int,int,char[],int,int,int)
private int lastIndexOfSupplementary(int,int)
public int length()
public boolean matches(String)
private boolean nonSyncContentEquals(AbstractStringBuilder)
public int offsetByCodePoints(int,int)
public boolean regionMatches(int,String,int,int)
public boolean regionMatches(boolean,int,String,int,int)
public String replace(char,char)
public String replace(CharSequence,CharSequence)
public String replaceAll(String,String)
public String replaceFirst(String,String)
public String[] split(String)
public String[] split(String,int)
public boolean startsWith(String,int)
public boolean startsWith(String)
public CharSequence subSequence(int,int)
public String substring(int)
public String substring(int,int)
public char[] toCharArray()
public String toLowerCase(Locale)
public String toLowerCase()
public String toUpperCase()
public String toUpperCase(Locale)
public String trim()

It can be seen that through class objects, we can dynamically obtain the properties and methods in a class and call them. Class objects are also the basis for our usual use of reflection.

(4) Loading of array classes

The case of creating an array class is slightly special, because the array class itself is not created by the class loader, but directly created by the JVM as needed at runtime, but the element type of the array still needs to be created by the class loader. The process of creating an array class (hereinafter referred to as A):

  • 1. If the element type of the array is A reference type, follow the defined loading process to recursively load and create the element type of array A;
  • 2. The JVM uses the specified element type and array dimension to create a new array class;

If the element type of the array is a reference type, the accessibility of the array class is determined by the accessibility of the element type. Otherwise, the accessibility of the array class will be defined as public by default.

3, Summary

The above is the introduction to the first stage of class loading - loading. In general, the main tasks of the loading stage are:

  • Obtain the binary data stream of the class through the full name of the class;
  • The binary data stream of the parsing class is the dynamic data structure of the runtime in the method area (Java class model);
  • Create Java. Net in the heap An instance of lang. class class, which is used to represent this type and serves as an access entry for various data of this class in the method area;

Keywords: Java jvm

Added by pastet89 on Sun, 19 Dec 2021 07:08:04 +0200