Java basics notes -18- class loading mechanism and reflection

Java basics notes -18- class loading mechanism and reflection

Loading a class, and the connection initialization

1.1 JVM and class

When you run a Java program calls the Java command that will start a Java virtual machine process, no matter how complex the Java program has, when the program started how many threads, they are in the Java virtual machine in the process. As described earlier, with all the threads of a JVM, all variables are in the same process, they are using the memory area of ​​the JVM process. When the system following situations, JVM process will be terminated.

  • The program runs to the end of the last normal
  • Used to run System.exit()or Runtime.getRumtime().exit()the end of the program codes.
  • During program execution encounters an uncaught exception or error ended
  • Platform where the program is forcibly terminated JVM process

The following class variables to classes to illustrate the problem. The following procedure defines a first class containing a class variable

//A.java
public class A {
    //定义该类的类变量
    public static int a=6;
}

Program code for bold above defines a class of a variable, the next to create an instance of a class defined in the Class A, A and access the object class variables a

//ATest1.java
public class ATest1 {
    public static void main(String[] args) {
        //创建A类的实例
        A a=new A();
        //让a实例的类变量a的值自加
        a.a++;
        System.out.println(a.a);
    }
}

A program can also create the following objects, and access the value of a variable whose class

//ATest.java
public class ATest2 {
    public static void main(String[] args) {
        //创建A类的实例
        A b=new A();
        //输出b实例的类变量a的值
        System.out.println(b.a);
    }
}

The first two results a second output 7 output 6, two runs twice running JVM process, after the first run JVM, he made for Class A modified will be lost --- second run A JVM will initialize class again

1.2 class loading

When the program is actively using a class if the class has not been loaded into memory, the system will by loading, connected to the initialization step the three classes initialized. If there is no accident, JVM will do this three successive steps, so sometimes these three steps collectively referred to as class loading or class initialization.

Class load refers to the class of the class file is read into memory, and whom to create a java.lang.Classtarget, that is, when the program in any class, whom the system will establish a java.lang.Classtarget

Class by the class loader loaded, the class loader is usually provided by the JVM, the class loader is the basis for all front running, these provide the JVM class loader is generally referred to as system class loader. In addition, developers can also create your own ClassLoader class loader by inheriting the base class.

By using a different class loader, the binary data from different sources can be loaded classes are usually several sources.

  • Class is loaded from the local file system, which is the majority of the front loading type sample program.
  • Load class files from the package JAR
  • Load class files over a network
  • Put a dynamically compiled Java source file, and perform load

Class loader is no need to wait until the city "first use" class when the class is loaded, Java Virtual Machine Specification allows the system to pre-load some classes

Class 1.3 is connected

When after the class is loaded, the system generates a corresponding whom Class object, then the connection will enter the stage, the connection phase is responsible for merging data into binary classes in the JRE, type connector is divided into the following three stages

  • Verification: Verify test phase for the loaded class has the correct internal structure, and coordinated with other classes
  • Preparation: class preparation phase is responsible for the class variable class of allocating memory, and set the default initial value
  • Analysis: The binary data class replaced symbolic references cited directly

1.4 initialization class

In the class initialization phase, the virtual machine is responsible for the class to initialize the main thing is the class variables are initialized. There are two ways to specify the initial value of the class variable in a Java class: ① class variable declaration specifies the initial value; ② using static class variables initialization block specified initial value. For example, the following code fragment.

public class Test {
    //声明变量a时指定初始值
    static int a=5;
    static int b;
    static int c;
    static{
        //使用静态初始化块为变量b指定初始值
        b=6;
    }
    ...
}

For the above code, a program for class variables a, b are explicitly specifies an initial value, 5,6, but the class variable c is not specify an initial value, he will use a default initial value 0.

Specifies the initial value declared variables, static initialization block will be initialized as a class statement, the JVM will order the program sequentially executes them in these statements, for example, the following classes.

Test.java
public class Test {
    static {
        //使用静态初始化块为变量b指定初始值
        b=6;
        System.out.println("--------");
    }
    //声明变量a时指定初始值
    static int a=5;
    static int b=9;
    static int c;
    public static void main(String[] args){
        System.out.println(Test.b);
    }
}

The above code is first assigned to the variable b in the static initialization block, in which case the value of variable b class 6; program execution then down again until the program assigned to the variable b. Finally, the value of variable b 9.

JVM initializes a class comprising the following steps

  1. If this class has not been loaded and connected, and then connected to a program loads the class
  2. If the direct parent class has not been initialized, it first initializes its direct parent
  3. If the class initialization statements, the system sequentially performs the initialization statements

When performing the second step, system initialization step also follows the direct parent 1-3, if there are direct parent, repeat steps 1-3, to be used to ensure that all the parent class (parent class directly or indirectly parent) are initialized.

1.5 class initialization time

When a Java program for the first time to use a class or interface through six ways, the system will initialize the class or interface

  • Create an instance of the class. Examples of a method for creating a class comprising: using the new operator to create an instance to create an instance by reflection, to create an instance by way deserialized
  • Call the class method (static methods) of a class
  • Access class variables of a class or interface, or variable assignment for the class
  • Reflection mode using force the creation of a class or interface objects corresponding java.lang.Class
  • Subclass initialization of a class.
  • To run a master class directly java.exe command. When running a master class, the program will first initialize the main class

In addition, following several cases of particular note

For a final type of class variable, if the value of the class variable at compile time can be determined, then the class variables is equivalent to "macro variables." Java compiler will directly replace at compile time, this place is a class variable that appears to its value, even if the program uses the static class variable, it will not cause class initialization. The following exemplary procedure

class MyTest {
    static {
        System.out.println("静态初始化块...");
    }
    //使用一个字符串直接量为static final的类变量赋值
    static final String compileConstant="疯狂Java讲义";
}
public class CompileConstantTest {
    public static void main(String[] args) {
        //访问,输出MyTest中的compileConstant类变量
        System.out.println(MyTest.compileConstant); //①
    }
}

Chapter MyTest class above procedures have a compileConstant class variables, which uses a variable final modification, and its value can be finalized at compile time, so compileConstant will be treated as "macro variables" process. All programs use compileConstant places will be a direct replacement to its value --- that is, the code above program at ① will be replaced with "crazy Java handouts" at compile-time, all lines of code will not lead ① MyTest class initialization.

Conversely, if the final modified class variables can not be determined at compile time down, you must wait until run time to determine the value of such variables, if it is to access class variables This class will lead the class is initialized. Defined above, for example, the program code read as follows compileConstant

//采用系统当前时间为static final类变量赋值
static final String compileConstant=System.currentTimeMills()+"";

Because the value of cimpileConstant class variables defined above must be determined at runtime, so the code in bold at ① must retain a reference to the class variables MyTest class, which lines of code into a class MyTest variables, which will lead to MyTest class is initialized.

When using the ClassLoader class loadClass()time to load a class method, which simply loads the class, and does not perform the initialization of the class. Use Class of forName()static methods would lead to forced initialize the class.

Guess you like

Origin www.cnblogs.com/whatsabc/p/11520913.html