#类加载器 and Reflection
# #类的加载, Connect and initialize
# # #JVM和类
When a jave program is run, no matter how complex the program is, it will eventually be loaded into the Java Virtual Machine (JVM) process. All of the same JVMThreadsAllvariablesare in the sameProcess, the memory area of the JVM process is used (note the difference between the process and the thread).
case where the JVM process was terminated
1. program run to normal end
2. Program run System.exit () or Runtime.getruntime (). Exit () method
3. End of an uncaught or error encountered during program execution
4. The platform on which the program is being forced to end the JVM
# # #类的加载
When the program actively uses a class and the class is not loaded into memory, the system performs the following three steps to initialize the class
1. Loading
is to read the class file into memory and create a java.lang.class object, when any class is used in the program, The system creates a Java.lang.class object, the load of the class is done by the ClassLoader, the ClassLoader is provided by the JVM, and the ClassLoader is the basis for all programs to run; The class loader provided by the JVM is called the system ClassLoader .
Different classloader that can convert classes from different sources into binary data, often with several sources
- Load a class file from a local file (most commonly used)
- Load a class file from the jar package (also common, by using the JDBC Connection database)
- Load class files over the network
- Dynamically compiles a Java source file and executes the load
2. Connect
When the class is loaded, the system generates a class object, followed by a connection , which is responsible for merging the class's binary data into the JRE
(The JRE is the Java Runtime Environment abbreviation, which refers to the Java Runtime Environment, which is Sun's product.) A collection of environments necessary to run a Java program, including the JVM standard implementation and the Java Core Class library
3. Initialization
Initialization of classes in Java in two ways (both ways, the system executes from top to bottom in the code)
1. Declaring class variables
static int a=5
2. Specifying an initial value for a class variable using a static initialization block
static int b;
static{
B=6
}
The JVM Initializes a class that consists of the following steps
1. If the class has not been loaded and connected , the program loads and connects the class first
2. If the immediate parent class of the class has not been initialized, the immediate parent class should be initialized first
3. If there are initialization statements in the class, the system executes the initialization statements sequentially
In 2, the system also follows these three steps to initialize the immediate parent class, so java.lang.Object (superclass) , this class is first initialized
The time of class initialization
When a Java program uses a class or interface, the system initializes the class or interface;
1 Create an instance of the class (including new create instance, reflect, deserialize)
2 calling a method of a class (static method)
3 Accessing class variables of a class or interface, or assigning a value to the class variable
4 forces the creation of a Java.lang.Class object for a class or interface using reflection, such as class.forname ("person"), which initializes the class directly and returns the Java.lang.Class object of that class.
5 initializes the subclass of the class, and the child class's parent class is also initialized
6 run Java.exe directly to run a main class, the program initializes the main class
Initialize Exception cases
The following program is an exception, when the final shape of the class variable, when the class is compiled, the value of the variable is already determined (is the step of loading is determined), the final modified variable becomes a macro variable, So when the main program calls Testcalss.contantvlaue, the Testcalss class is not initialized.
Package com.test;
Class testcalss{
static{
SYSTEM.OUT.PRINTLN ("Initialize this class");
}
Static final String contantvlaue= "final Bianliang";
}
public class Test1 {
public static void Main (string[] args) {
System.out.println (Testcalss.contantvlaue);
}
}
If the final modified class variable cannot be confirmed at the time of the program's compilation, it must wait for the runtime to determine the value of the class variable, and if the class variable is accessed through that class, it will cause the class to be initialized
For example, put the static final String Contantvlaue=system.currenttimemillis () + "";
# #类加载器
The ClassLoader is responsible for loading the. class file (which can be stored on disk or on the network) into memory and generating the corresponding Java.lang.class object (there is no need to be overly concerned with the classloader in development to understand how the mechanism works)
# # #初始化类加载器的组成
When the JVM starts, it is composed of three class loaders that initialize the ClassLoader hierarchy
- Bootstrap ClassLoader: Root loader--the core class that is responsible for loading Java (such as basic variables such as String), is not a subclass of Java.lang.ClassLoader, but is implemented by the JVM itself
- Extension ClassLoader: Extension Class Loader-the class that is responsible for loading jar packages in the JRE's extended directory (%java_home%jre/lib/ext), in this way, can extend new functionality outside of the core class for JAVA, Just pack the class you developed into a jar file and put it in the%java_home%jre/lib/ext path
- System ClassLoader: Systems ClassLoader--responsible for loading the-classpath option from Java when the JVM is started, Java.call.path the System properties, or the jar package and classpath specified by the CLASSPATH environment variable
# # #类加载机制
1. Overall responsibility: When a classloader is responsible for loading a class, the class is dependent on and the other classes that are applied are also loaded by the ClassLoader. (Fully owned by a classloader)
2. Parent class Delegate: An attempt was made to load the class by the parent class loader before attempting to load the class from its own classpath only if the class loader cannot load the class.
3. Caching mechanism: Ensure that all parent-state classes are cached and loaded directly when the program needs to use a class
Get the system ClassLoader code
ClassLoader Systemloader=classloader.getsystemclassloader ();
Gets the system ClassLoader's parent class loader, gets the extension class loader
ClassLoader extensionlader=systemloader.getparent ();
All class loaders except the root ClassLoader in the JVM are instances of the ClassLoader subclass, ClassLoader's common implementation class, which is also the parent class of the system ClassLoader and extension class loaders; URLClassLoader powerful, Binary files can be loaded from the local file system, or binaries can be obtained from the remote host to load the class
# #通过反射查看类的信息
There are two types of Java objects at run time, 1. Compile-time type and run-time type. For example, Person p=new Student (); This line of code generates a P variable with a compile-time type of person, a run-time type of Student, and a program that accepts an externally passed-in object at run time, the compile-time type is object, However, the program calls the method of the object's run-time type. In order to discover real information about objects and classes while the program is running, there are two ways
- Assuming that the exact information about the object and the class is fully known at compile time and at run time, you can use the instanceof operator to judge it, and then convert it to a variable of the run-time type using a cast-type conversion.
- At compile time, it is impossible to predict which classes the object and class might belong to, and the program relies only on runtime information to discover the real information of the object and class, and it must use the thought of reflection.
# # #获得Class对象
After each class is loaded, a corresponding class object is generated for the class that can access the class in the JVM.
1. Using the class forname (String className) static method, pass in the fully qualified class name of the class (full package name)
2. Use the Class property of the classes to get the class object for the classes, for example, Person.class will return the class object corresponding to the person class
3. Call the GetClass () method of an object. This method is a method in the Java.lang.Object class. All Java objects can call the method, which returns the class object that the object belongs to.
For the first and second methods, the class object is obtained directly from the class, in contrast, the second method has the following two advantages.
1. The code is more secure. The program can check the existence of the class object to be accessed during the compilation phase
2. Better program performance. The method cannot be called in this way, the performance is better
# # #可以从Class中获取哪些信息?
- Constructor Constructor GetConstructor ()
- Menthod Gets the method GetMethod () contained in class corresponding classes
- Accesses the member variables contained in class corresponding classes GetFields ()
- Get several methods the user accesses the annotation getannotation () contained on class corresponding classes
- You can also judge the method to determine whether the class is an excuse, enumeration, annotation type, etc.
Tips: Overloading: Method names are the same, but parameter lists are different. To determine a method in Java, there is not enough method name, it should be determined by the method name and formal parameter list (the parameter name is meaningless and must depend on the parameter type).
For example, there are three methods
1. public void info()2. public void info(String str)3. public void info(String str,Integer num)
To specify a second info method, get the method code in the program as follows
Class.getmethod ("info", String.class)
Specify the third info with the following code
Class.getmehtod ("info", String.class,integer.class)
# #使用反射生成操作对象
Class object can get the method in the class, constructor (Constructor), member variable (Field)
# # #利用反射创建对象
Two different ways
- Use the Newinstance () method of the class object to create instances of the class object's corresponding classes, but require that the class object's corresponding classes have a default constructor, and when the Newinstance () method is executed, the default constructor is actually used to create an instance of the class----- The most common method
- Use the Class object to specify the constructor object, and then call the Newinstance () method of the constructor object to create an instance of the corresponding class of the class object. This way you can choose to create an instance using the specified constructor.
The following example uses the thought of reflection to generate objects using the first method of newinstance, creating objects similar to those generated by spring.
Package Com.test;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstream;import Java.util.hashmap;import Java.util.Map;import Java.util.properties;import Java.util.set;public class Objectpoolfactory {private map<string,object> Objectpool=new hashmap<string, object> ();p rivate Object CreateObject (String ClassName) throws Instantiationexception, Illegalaccessexception, classnotfoundexception{class<?> clazz=Class.forName ( ClassName); return clazz.newinstance ();} Location of the incoming file store public void Initpool () throws IOException, Instantiationexception, Illegalaccessexception, classnotfoundexception{try {//d:/test/a.properties InputStream fis=new FileInputStream (The New File ("D:/tes T/a.txt ")); Reads the information in the properties file {Properties Props=new properties (); Props.load (FIS); System.out.println ("InitPool1"); Iterate through the information in the properties file and according to the props fileCreates an object in the fully qualified name of the class and puts it into the object pool set<string> stringpropertynames = Props.stringpropertynames (); System.out.println (Stringpropertynames.isempty ()); for (String name:stringpropertynames) {//stored in the form of a class's permission-set name, the object is stored in the object pool System.out.println ("Initpoo L2 "+props.getproperty (name)); Objectpool.put (Name, CreateObject (Props.getproperty (name))); }}} catch (FileNotFoundException e) {System.out.println ("not loaded into file"); E.printstacktrace (); }}//returns objects public object GetObject (String className) throws Instantiationexception, Illegalaccessexception, classnotfoundexception {//system.out.println (Objectpool.get (className)); Return Objectpool.get (className);} public static void Main (string[] args) throws IOException, Instantiationexception, Illegalaccessexception, classnotfoundexception {objectpoolfactory pool= new objectpoolfactory (); Pool.initpool (); System.out.println (Pool.getobject ("a")); SYSTEM.OUT.PRINTLN (POol.getobject ("B"));}}
If you do not want to build the object in a way that is the default constructor, you can use constructor to specify the constructor to generate the object. Steps are as follows
- Get the Class object
- Use the GetConstructor () method of the class object to get the specified constructor
-
Call Constructor's Newinstance () method to create a Java object
' public class Test2 {
public static void Main (string[] args) throws Exception {
Get the class object for Jframs
class<?> JFrame = Class.forName ("Javax.swing.JFrame");
Gets the constructor with parameters in the Jframs class object
Constructor Ctor=jframe.getconstructor (String.class);
Generates an Jframs object, because the constructor has parameters, so the object is generated with a string type argument
Object object = Ctor.newinstance ("123");
System.out.println (object);
}
Reflection Summary : It is generally not necessary to create objects through reflection, because of the low performance, in fact, only when the program needs to dynamically create a class of objects to consider the use of reflection, usually more versatile framework, it is possible to use a large number of reflection (Spring).
# # #调用方法
When you get the class object for a category, you can get all the methods through the Class object's GetMethods () method or the Getmehtod () method or specify the method
GetMethods () Gets all the methods, the return value is an array
GetMethod (), gets the specified method, returns the Methods object
Method contains an invoke (), signed as follows
Object Invoke (Object Obj,object...args): The method in which obj is the keynote that executes the method, and the following args is the argument that executes the method
Thoughts on JAVA Reflection