Java Reflection-----from class loading

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Absrtact: This paper mainly discusses the mechanism of Java class loading, which is the basic of learning reflection.


first, class loading

JVM and Class

When we call the Java command to run a Java program, the command will start a Java Virtual machine process, no matter how complex the Java program is, how many threads the program launches, all in the Java Virtual machine process. As described earlier, all threads of the same JVM, all variables are in the same process, and they all use the memory area of the JVM process. The JVM process is terminated when the system has the following conditions:

1, the program runs until the end of normal.
2, the program runs to use System.exit () or Runtime.getruntime (). exit () code to end the program.
3, the program execution process encountered an uncaught exception or error and ended.
3, the program is on the platform to force the end of the JVM process.
As you can see from the above introduction, when the Java program finishes running, the JVM process ends and the process in memory state is lost.

Life cycle of a class

Class for Load/class initialization

When the program actively uses a class, if the class has not been loaded into memory, the system will be loaded, connected, initialized three steps to initialize the class, if there is no accident, the JVM will complete the three steps, so sometimes the three steps are collectively referred to as class loading or class initialization.

Loading: Finding and loading binary data for a class

1. Obtain a binary byte stream that defines this class by using the fully qualified name of a class.
2. Transform the static storage structure represented by this byte stream into the runtime data structure of the method area.
3. Generate a Java.lang.Class object representing this class in the Java heap as the access entry for the data in the method area.

note: The compiled java java.lang.class class java.lang.class class object is unique!
connection:

        1: Verify that the class being loaded is correct
        2, preparing to allocate memory for static variables of a class and initialize it to the default value
        3, parse: Converts a symbolic reference in a class to a direct reference.
initialization: Assigns the correct initial value to the static variable of the class.

Note: During the connection and initialization phase, static variables are assigned two times: the first is the default value of the static variable type, and the second is the value that we really assign to the static variable.

I drew a simple diagram with the following process:


class loading refers to reading class files into memory and creating a Java.lang.Class object for them. This means that when you use any class in your program, the system creates a java.lang.Class object for it. In fact, each class is an abstraction ( or concept )of a group of objects with the same characteristics, and all of theclasses in the system, which are actually objects, are An instance of Java.lang.Class.

Loading is done by the class loader, which is typically provided by the JVM, which is also the basis for all of our previous programs to run, and these classloader are often referred to as the System class loader. In addition, developers can create their own class loaders by inheriting the ClassLoader base class.


By using different ClassLoader, you can load the binary data of a class from different sources, usually with the following sources:

1. Load the class file from the local file system, which is the class loading mode for most of the sample programs.
2, loading the class file from the jar package is also very common, the database driver class used in the previous introduction of JDBC programming is placed in the jar file, the JVM can directly load the class file from the jar file.
3. Load the class file through the network.
4. Dynamically compile and load a Java source file.


The class loader typically does not have to wait until the class is first used, and the Java Virtual Machine specification allows the system to preload some classes.

How the Java program uses the class
Active use

1. Create an instance of the class
2. Method A static variable for a class or interface, or assign a value to the static variable
3. Static method of calling class
4, reflection (such as Class.forName ("Com.itzhai.Test"))
5. Initializes a subclass of a class
6. Class (Main Class) that is marked as the startup class when the Java virtual machine is started

Passive use
In addition to the above 6, other uses of the class are passive and do not result in the initialization of the class. Class initialization time is the first active use of the Java program for the class.
All Java Virtual machine implementations must initialize each class or interface when it is "first active" by the Java program.

Object initialization
When classes are loaded, concatenated, and initialized, the class is ready to be used. Object instantiation and initialization are activities that are the beginning of the object's life, where we mainly discuss the characteristics of the initialization of the object.
The Java compiler generates at least one instance initialization method for the class when compiling each class-the "<init> ()" method. This method corresponds to each constructor method in the source code, and if the class does not explicitly declare any constructor methods, the compiler generates a default parameterless constructor for that class, which simply calls the parent class's parameterless constructor, and at the same time generates a "<init" that corresponds to the default constructor method. > () "Method.
In general, the code included in the,<init> () method might be: Call another <init> () method, initialize the instance variable, and the code within its corresponding constructor method.
If the constructor is explicitly started by invoking another constructor in the same class, then its corresponding <init> () method body includes a call to the <init> () method of this class, and all bytecode within the constructor method applied.
If the constructed method does not start by calling other constructors of its own class, and the object is not an object, then the <init> () method includes a call to the parent class <init> () method, and a byte code for the instance variable initialization method The last is the method body bytecode corresponding to the constructor.
If this class is Object, then its <init> () method does not include a call to the parent class <init> () method.


second, Class.forName, instance object. Class (attribute), instance object GetClass () difference

1, the same point:
In these ways, the Java.lang.Class object is obtained (this is the final product that the class mentioned above is loaded with)
For example:

Package com.lin;/** * Feature Summary: *  * @author Linbingwen * @since  October 20, 2015  */public class People {/** * @author l Inbingwen * @since  October 20, 2015  * @param args     */public static void Main (string[] args) throws Exception {Syste M.out.println ("......") Load classes in different ways ............ "); System.out.println (People.class);//The class object people a = new people () is obtained by classes. Class. System.out.println (A.getclass ());//Get Class Object System.out.println (Class.forName ("Com.lin.people") by instance name. GetClass () )///through Class.forName (full path) to obtain the class object System.out.println ("... Create an object in a different way .......... "); System.out.println (a);//Create Object System.out.println (People.class.newInstance ()) using different methods; System.out.println (A.getclass (). newinstance ()); System.out.println (Class.forName ("Com.lin.people"). newinstance ()); }}

Results:


You can see different ways to load classes from above. In fact, this process only happens once!

2. Difference:

Here's an example of the difference between them.

Create a new class as follows

Package com.lin;/** * Feature Summary: *  * @author Linbingwen * @since  October 20, 2015  */public class Cat {static {System.out . println ("generated a Cat");}}

Then start using:

Package com.lin;/** * Feature Summary: *  * @author Linbingwen * @since  October 20, 2015  */public class Cattest {/** * @author Linbingwen * @since  October 20, 2015  * @param args     */public static void Main (string[] args) throws exception{ System.out.println ("---------------cat.class start------------------"); System.out.println (Cat.class),//through class. class to Get the Class object System.out.println ("--------------- Cat.class end------------------"); System.out.println ("---------------class.forname start------------------"); System.out.println (Class.forName ("Com.lin.Cat"));//through Class.forName (full path) to obtain the Class object System.out.println ("---------- -----class.forname End------------------"); System.out.println ("---------------cat.getclass () Start------------------"); Cat cat = new Cat (); System.out.println (Cat.getclass ());//through Class.forName (full path) to obtain the class object System.out.println ("--------------- Cat.getclass () End------------------");}}
Output Result:

If, remove the Class.forName ():

As follows:

Package com.lin;/** * Feature Summary: *  * @author Linbingwen * @since  October 20, 2015  */public class Cattest {/** * @author Linbingwen * @since  October 20, 2015  * @param args     */public static void Main (string[] args) throws exception{ System.out.println ("---------------cat.class start------------------"); System.out.println (Cat.class),//through class. class to Get the Class object System.out.println ("--------------- Cat.class end------------------");//system.out.println ("---------------class.forname start------------------");// System.out.println (Class.forName ("Com.lin.Cat"));//through Class.forName (full path) to obtain the Class object//system.out.println ("-------- -------Class.forName End------------------"); System.out.println ("---------------cat.getclass () Start------------------"); Cat cat = new Cat (); System.out.println (Cat.getclass ());//through Class.forName (full path) to obtain the class object System.out.println ("--------------- Cat.getclass () End------------------");}}

The result becomes:


Therefore, the following conclusions can be drawn:

1) Class Cl=cat.class; The JVM will use class-Cat's class loader to load Class A into memory (provided that class A is not loaded into memory) and class A does not initialize Class A. Returns the object of Class A's class
2) Class cl= object reference O.getclass (); returns an object that references the class that the runtime actually refers to (because: a reference to a son object may be assigned to a reference variable in the parent object), and if it has not yet been loaded, it is loaded.
3) Class.forName ("Class name"); Load Class A and initialize the class (provided that Class A is not loaded in memory)

Iii. New and newinstance ()

From the JVM's point of view, when we use the keyword new to create a class, the class can not be loaded. However, when you use the Newinstance () method of the Class object, you must ensure that:

1, this class has been loaded;

2, this class has been connected. The two steps above are done by the static method of Class forname (), which invokes the startup ClassLoader, the one that loads the Java API.

As you can see, the newinstance () of the class object (which is similar to the factory pattern in Java) actually breaks the new approach into two steps, that is, the class loading method is called first to load a certain classes and then instantiate. The benefits of this step are obvious. We can get better flexibility when invoking the static Load method of class forname, providing a means of decoupling.

Class.forName (). newinstance () and the difference between objects obtained by new


1, using newinstance can be decoupled. The premise of using newinstance is that the class is loaded and the class is connected, which is exactly what the static method of Class forname () is doing. Newinstance actually breaks the new approach into two steps, that is, to first call the class's Load method to load a category and instantiate it.

2, Newinstance: weak type. Low efficiency. Only parameterless constructs can be called. NEW: Strongly typed. relatively efficient. Can invoke any public construct.

3, Newinstance () is the implementation of the IOC, reflection, face interface programming and dependency inversion of the technical methods of the inevitable choice, new can only achieve the specific instantiation of the class, not suitable for interface programming.

4, newinstance () is generally used for dynamic load classes.

5, Class.forName (""). Newinstance () returns an object.

6, Newinstance () is a method, and new is a keyword;

Note: Generally used in the general framework of the use of Class.forName to load the class, and then through reflection to invoke the method, such as Tomcat in the source, so that the new keyword to avoid the coupling, and let the different class loader to load different classes, Easy to improve security and isolation between classes.


Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, reproduced please indicate the source Http://blog.csdn.net/evankaka

Java Reflection-----from class loading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.