Deep understanding of Java: class loading mechanism and reflection
1. summary after the Class file is loaded by the Class loader, a metadata object describing the Class structure will be formed in JVM. The metadata object can be used to obtain the structure information of the Class, such as the constructor, attributes and Methods. Java allows you to indirectly call the Class object function by using the metadata object related to this Class. The Virtual Machine loads the description class data from the class file to the memory, verifies the data, converts the parsing and initialization, and finally forms the Java type that can be directly used by the virtual machine, this is the class loading mechanism of virtual machines. 2. Working mechanism the class loader is to find the class bytecode file and construct the object component represented by the class in JVM. In Java, if the Class loader loads a Class into JVM, perform the following steps: (1) load: Find and import the Class file; (2) link: merge the binary data of the Class into JRE. (a) Check: Check the correctness of the data loaded into the Class file; (B) prepare: allocate storage space to the static variables of the Class; (c) resolution: convert a symbolic reference to a direct reference; (3) initialization: static variables of the class, static code blocks perform initialization operations. Java programs can be dynamically expanded by dynamic loading and dynamic links at runtime. For example, if you compile an application using an interface, you can specify the actual implementation (polymorphism) at runtime. The parsing process can also be executed after initialization. For example, dynamic binding (polymorphism) and class initialization (1) in the case of the new, getstatic, putstatic, or invokestatic bytecode commands, if the class has not been initialized, you must first trigger its initialization. The most common Java code scenario for generating these four commands is: when an object is instantiated using the new keyword, when reading or setting static fields of A Class (except static fields modified by final, which are put into the constant pool during compilation) and calling static methods of a class. (2) when using the java. lang. reflect package method to call the class reflection, if the class has not been initialized, it needs to be triggered first. (3) When initializing a class, if you find that the parent class has not been initialized, you must first trigger the initialization of the parent class. (4) When a virtual machine is started, you need to specify a main class to be executed (the class containing the main () method). The virtual opportunity first initializes the main class. Only the above four situations will trigger initialization, also known as active reference to a class. In addition, all other methods will not trigger initialization, which is called passive reference after the above Code is run, only "--- SuperClass init" is output, and "SubClass init" is not output. For static fields, only classes that directly define this field are initialized. Therefore, the static field of the parent class is called by subclass, which only triggers the initialization of the parent class, but it depends on different implementations of different virtual machines. This will not cause SuperClass initialization, but triggers [[Ltest. superClass initialization, through arr. toString () can be seen that for user code, this is not a legal class name, it is automatically generated by the virtual machine, directly inherited from the Object subclass, the creation action is triggered by the bytecode instruction newarray. At this time, the array out-of-bounds check is also accompanied by all the calling processes of the array object. The out-of-bounds check is not encapsulated in the class accessed by array elements, it is encapsulated in the xaload and xastore bytecode commands accessed by arrays. constClass. the reference of value is actually converted to the reference of the NotInitialization class to its own constant pool. There is no connection between the two classes after being compiled into the class. [Loading] in the loading phase, the virtual machine needs to complete the following three tasks (1) Get the binary byte stream that defines this class through the full qualified name of a class (2) convert the static storage structure represented by this byte stream into the runtime data structure of the Method Area (3) generate a Java heap representing this class in java. lang. class Object, used as the access entry to the data in the method area. The virtual machine specification does not accurately describe where the binary byte stream should be obtained and how to obtain it. Here, you can define your own class loader to control the byte stream acquisition method. [Verification] If the virtual machine does not check the input byte stream and fully trusts it, it is likely that the system will crash due to loading harmful byte streams. [Preparation] the preparation stage is the stage in which class variables are officially allocated and the initial values of class variables are set. These memories will be allocated in the method area. It should be noted that: at this time, the memory allocation only includes class variables (static modified variables), but does not include instance variables. instance variables will be allocated to the Java heap along with the object during Object Instantiation; the initial value "usually" is the zero value of the data type. For example, public static int value = 123; the initial value of value after the preparation stage is 0 rather than 123, the putstatic command for value assignment will be executed only in the initialization phase. 2. The class loader and the parent delegate model Class Loader (1) Bootstrap ClassLoader: it will be stored in the <JAVA_HOME> \ lib directory, or in the path specified by the-Xbootclasspath parameter, and recognized by the VM (only by file name, such as rt. libraries with invalid jar names are not loaded even in the lib directory .) Memory of the VM. The Class Loader cannot be directly referenced by Java programs. (2) Extension ClassLoader: Directory <JAVA_HOME> \ lib \ ext, or. ext. all class libraries in the path specified by dirs system variables are loaded. Developers can directly use the extension class loader. (3) Application ClassLoader: loads the specified class library on the user ClassPath, which can be directly used by developers. Parent-Child Delegation Model Working Process: If a Class Loader receives a class loading request, it first delegates the request to its parent class loader to complete the process, this is true for class loaders at each level. Therefore, all loading requests should be sent to the top-level startup class loaders, only when the parent loader reports that it cannot complete the load request (it does not find the desired class in the search range) Will the child loader attempt to load it by itself. Benefit: a java class has a level of priority along with its class loader. For example, java. lang. object, which is stored in rt. in jar, no matter which class loader needs to load this class, it will eventually Delegate to the startup Class Loader for loading, therefore, the Object class is the same class in the loader environment of various types of programs. On the contrary, if you write a file named java. lang. object Class and put it in the program's Classpath. Then, there will be multiple different Object classes in the system, and the most basic behavior in the java type system cannot be guaranteed, applications can also become messy. Several of the most important methods in java. lang. ClassLoader are: copy the code // load the binary type of the specified name (including the package name) for the public Class interface called by the user <?> LoadClass (String name); // load the binary type of the specified name (including the package name), and specify whether to parse (however, the resolve parameter here does not necessarily achieve the resolution effect.) protected synchronized Class can be used for inheritance. <?> LoadClass (String name, boolean resolve); protected Class <?> FindClass (String name) // defines the type. It is generally called after the corresponding bytecode is read in the findClass method. It can be seen that it cannot be inherited (Note: JVM has implemented the corresponding functions, parse the corresponding bytecode to generate the corresponding internal data structure and place it in the method area. Therefore, you can directly call it without overwriting.) protected final Class <?> DefineClass (String name, byte [] B, int off, int len) throws ClassFormatError {} copy the Code as follows: iii. Reflection mechanism allows the program to use Reflection APIs to obtain internal information of any class with a known name during execution, including: package, type parameters, superclass, implemented interfaces, inner classes, outer classes, fields, constructors, methods, modifiers, etc. During execution, dynamically generate instances, change fields content, or invoke methods. 1. Obtain the constructor Class provides four public methods to obtain the constructor of a Class. Constructor getConstructor (Class [] params) returns a specific Constructor getConstructors () with public Attributes Based on the Constructor parameters () returns the Constructor getDeclaredConstructor (Class [] params) array of all constructors with the public attribute. Returns a specific Constructor getDeclaredConstructors () based on the Constructor parameters () returns the array of all constructors in the class (regardless of the public and non-public attributes). 2. The methods for retrieving class members are the same as those for obtaining the constructor. There are four methods for obtaining member methods. Method getMethod (String name, Class [] params) returns a specific Method with the public attribute [] getMethods () based on the Method name and parameter () returns the Method getDeclaredMethod (String name, Class [] params) array of all methods with public attributes. Returns a specific Method based on the Method name and parameter (regardless of public and non-public attributes) method [] getDeclaredMethods () returns an array of all methods in the class (regardless of public and non-public attributes) 3. obtains the member variables (member attributes) of the class) there are four methods to get Member attributes Field getField (String name) returns a specific Field [] getFields () member variable with public Attributes Based on the variable name () returns the array Field getDeclaredField (String name) with the public attribute. Based on the variable name, returns a member variable (regardless of the public and non-public attributes) Field [] getDelcaredFields () returns an array composed of all member variables, regardless of public and non-public attributes)