Preface
In the study of Java Foundation, because the study is not solid, the practicality is not strong, feel useless, a lot of important knowledge on that kind of a pen, like this immediately to talk about the reflection mechanism, when learning to ignore, to later learning knowledge, a lot of things are still reflected, So back to give this to re-fill, their debts, sooner or later is to return.
---WH
First, what is reflection?
In the running state, all the properties and methods of the class can be obtained for any one class, and any one of its methods and properties (including private methods and properties) can be invoked for any object. This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the Java language's reflection mechanism. In layman's terms, by reflection, the class is completely transparent to us, and it is possible to acquire anything.
To use the reflection mechanism, you must first obtain the bytecode file object (. Class) of the class, and through the bytecode file object, you can get all the information we want (methods, attributes, class names, parent class names, all interfaces implemented, etc.) through the methods in the class. Each class corresponds to a byte-code file that corresponds to a class-type object, which is a bytecode file object.
Three ways to get a bytecode file object.
1, Class clazz1 = Class.forName ("Fully qualified class name"); Through the static method Forname in class classes, the bytecode file object of a class is obtained directly, at this time the class is still the source file stage , and it does not become a bytecode file.
2, Class clazz2 = Person.class; When a class is loaded into a. class file, the person class becomes a. class, in which the bytecode file object is acquired, that is, the class is in the bytecode phase .
3, Class clazz3 = P.getclass (); Gets the bytecode file object for the class through an instance of the class in the create object stage
With the bytecode file object to get all the information in the class, when we use reflection to get information, we also have to consider which way to get the bytecode object is reasonable, depending on the situation. The functions of the class are described below.
Second, what information can the reflection mechanism obtain? The class API is detailed.
2.1. Creating an instance object from a byte-code object
2.2. Gets the specified constructor method. constructor if there is no parameterless construct, only the argument constructs how to create an instance? Look underneath.
Summarize the above created instance object: The Class Newinstance () method is used to create an object using the parameterless constructor, and if a class does not have a parameterless constructor, it cannot be created and can call the class Getcon The Structor (String.class,int.class) method gets a specified constructor and then calls the constructor class's newinstance ("Zhang San", 20) method to create the object
Get all construction methods
2.3. Get the member variable and use the Field object
Gets the specified member variable
The Class.getfield (String) method can get the specified field in the class (visible) and, if it is private, can be obtained by using the Getdeclaedfield ("name") method, which sets the value of the field on the specified object through the set (obj, "John Doe") method. If it is private, you need to call Setaccessible (true) to set the access permission, and call Get (obj) with the specified field to get the value of the field in the specified object.
Get all member variables
2.4. Obtain methods and use method
Class.getmethod (String, class ...) and Class.getdeclaredmethod (String, class ...) method to get the specified method in the class.
If you are a private method, you need to open a permission. Setaccessible (TRUE);
Use Invoke (Object, Object ...) You can call this method,
As with the above, you can get all the methods at once.
2.5. Get all the interfaces for this class
Class[] Getinterfaces (): Determines the interface implemented by the class or interface represented by this object
Return value: An array of byte-code file objects for the interface
2.6. Get the input stream for the specified resource
InputStreamgetResourceAsStream(String name)
Return: A InputStream object, or null if no resource with that name is found
Parameter: The name of the resource you want, and if you start with "/", the absolute resource is named after the "/" section.
2.7. Dynamic Agent Overview and implementation
Dynamic Agent: A design pattern, it is very simple, very easy to understand, you can do this thing, but feel that you do very troublesome or inconvenient, so call a other person (agent) to help you do this thing, and you do not have to control, this is the dynamic agent. For example, buy a train ticket for someone to buy on behalf of.
This object is produced during the process of running the program, and the object that is generated during the program's operation is actually what we just reflected, so the dynamic agent is actually generating an agent through reflection.
In Java, a proxy class and a Invocationhandler interface are provided under the Java.lang.reflect package, and dynamic proxy objects can be generated by using this class and interface. The proxy provided by the JDK can only be proxied for the interface. We have more powerful proxies in the Cglib,proxy class to create a dynamic proxy class object
Three steps, but note that the agent provided by the JDK is capable of acting on the interface, that is, the second step below must be an interface.
1, new out of the proxy object, by implementing the Invacationhandler interface, and then new out of the proxy object.
2, through the proxy class static method Newproxyinstance, to the proxy object to pretend to be the object of the agent, that is, if people help us to buy train tickets, the agent pretended to be our own
3, the execution method, the agent succeeds
To implement the contents of a proxy object
1, 2, 3 steps
Note the three parameters of the Newproxyinstance, the first, the class loader, the interface of the second Proxied object, and the third proxy object.
2.8, there are many methods, such as the acquisition of class loader, and so on
You'll need something else, just by looking at the API documentation to fix it.
Application examples of reflection mechanism
3.1. Use reflection to hold a string object in the Arryalist collection of the generic type int
Principle: Generics in a collection are valid only in the compiler, and at run time, generics are invalidated.
3.2. Use reflection to simplify the number of servlet writers.
What do you mean? Whenever we write a function, we need to write a corresponding servlet, resulting in a lot of servlet, I can not see, so it was optimized, two ways,
3.2.1, each time from the page passed a parameter, method= "XXX"; Then write a servlet, get the value of its parameter method, make a judgment, if it is add, call the Add method, if it is delete, call the Delete method, so you can write in a servlet to implement all the functions.
3.2.2, using Reflection
Write a baseservlet inherited HttpServlet, which is a generic baseservlet. Need to understand the life cycle of the servlet
Write a concrete implementation of the method Servlet class.
MYSERLVET001 extends Baseservlet
Explanation: Need to understand the life cycle of the servlet, that is, the service method, because it is a servlet, so in the access time, will go through the service method, and sub-class MyServlet001 does not, so go to the parent class Baseservlet find, found that, Then get the parameters to know what method to call, because the method is written in the subclass, so through reflection, get to the corresponding method in the subclass and run, it is important to note that this parameter in the Baseservlet use. Need to understand it. To understand our program.
Iv. Summary
Reflection basically this is finished, in fact, some of its API to explain, do not understand the API, important ideas, it is necessary to meet in the actual to get a better understanding. Let's go through this, bits and pieces of knowledge.
A detailed explanation of the reflection mechanism in Java