Detailed explanation of reflection mechanism in Java

Preface

When learning the basics of Java, I didn't think it was useful because I didn't learn well and didn't speak practical. I took a lot of important knowledge in one stroke. Like the reflection mechanism to be talked about soon, I ignored it when I learned it. In the later knowledge, many things always use reflection, so I went back and supplemented it, The debt owed by yourself will be repaid sooner or later.

                                      ---WZY

1、 What is reflection?

In the running state, for any class, you can get all the properties and methods of the class. For any object, you can call any of its methods and properties (including private methods and properties). This dynamically obtained information and the function of dynamically calling the object's methods are called the reflection mechanism of Java language. Generally speaking, through reflection, this class is completely transparent to us. We can get anything we want.

To use the reflection mechanism, we must first obtain the bytecode file object (. Class) of the class. Through the bytecode file object, we can obtain all the information we want through the methods in the class (method, attribute, class name, parent class name, all implemented interfaces, etc.), Each class corresponds to a bytecode file, which corresponds to an object of class type, that is, a bytecode file object.

There are three ways to get bytecode file objects.

       1、Class clazz1 = Class. Forname ("fully qualified class name"); / / directly obtain the bytecode file object of a class through the static method forname in the class. At this time, the class is still in the source file stage and has not changed into a bytecode file.

       2、Class clazz2 = Person. class; / / when the class is loaded as Class file, the person class becomes Class, when getting the bytecode file object, that is, getting itself, this class is in the bytecode stage.

       3、Class clazz3 = p.getClass(); / / obtain the bytecode file object of the class through the instance of the class. The class is in the object creation stage

Only bytecode file objects can obtain all the information in the class. When using reflection to obtain information, we should also consider which of the above methods to obtain bytecode objects is reasonable, depending on different situations. The following describes the functions of class.

2、 What information can reflection mechanism get? Class API details.

2.1. Create instance objects through bytecode objects

2.2. Obtain the specified constructor method. How to create an instance of a constructor without a parameterless construct and only a parameterless construct? Look down

@H_ 403_ 55@

To sum up, create the instance object above: the newinstance () method of class class uses the class's parameterless constructor to create the object. If a class does not have a parameterless constructor, it cannot be created in this way, You can call the getconstructor (string. Class, int.class) method of class class to obtain a specified constructor, and then call the newinstance ("Zhang San", 20) method of constructor class to create an object

Get all construction methods

2.3. Get the member variable and use the field object

Gets the specified member variable

         Class. The getfield (string) method can obtain the specified field (visible) in the class. If it is private, it can be obtained with the getdeclaedfield ("name") method. The value of the field on the specified object can be set through the set (obj, "Li Si") method. If it is private, it is necessary to call setaccessible (true) to set the access permission, Call get (obj) with the obtained specified field to obtain the value of the field in the specified object

Get all member variables

2.4. Obtain method and use method

        Class. getmethod(String,Class...) And class getDeclaredMethod(String,Class...) Method can get the specified method in the class

If it is a private method, you need to open a permission. setAccessible(true);

Use invoke (object, object...) You can call this method,

In the same way as above, you can get all the methods at once

2.5. Obtain all interfaces of this class

Class [] getinterfaces(): determines the interface implemented by the class or interface represented by this object

Return value: array of bytecode file objects of the interface

2.6. Obtain the input stream of the specified resource

         InputStream getResourceAsStream(String name)  

Return: an InputStream object; If a resource with that name cannot be found, null is returned

Parameter: the name of the required resource. If it starts with "/", the absolute resource name is the part after "/".

2.7 overview and implementation of dynamic agent

Dynamic agent: a design pattern, which is very simple and easy to understand. You can do it yourself, but you think it is very troublesome or inconvenient, so you call another person (agent) to help you do it, and you don't have to worry. This is dynamic agent. For example, buy a train ticket and ask someone to buy it.

This object is generated during the running of the program, and the object generated during the running of the program is actually what we just explained by reflection. Therefore, the dynamic agent actually generates an agent through reflection

In Java, Java A proxy class and an invocationhandler interface are provided under the lang.reflect package. Dynamic proxy objects can be generated by using this class and interface. The agent provided by JDK can only act as a proxy for interfaces. We have a more powerful proxy cglib, and the methods in the proxy class create dynamic proxy class objects

There are three steps, but note that the agent provided by JDK can act as a proxy for the interface, that is, the returned interface in the second step must be an interface.

1. New out the proxy object, implement the invacationhandler interface, and then new out the proxy object.

2. Use the static method newproxyinstance in the proxy class to pretend that the proxy object is the proxy object, that is, if someone is asked to buy train tickets for us, the proxy will pretend to be ourselves

3. Execute the method and the agent succeeds

Implement the contents of the proxy object

Steps 1, 2 and 3

Note the three parameters of newproxyinstance: the first is the class loader, the second is the interface of the proxy object, and the third is the proxy object.   

2.8. There are many methods, such as obtaining class loader, and so on

If you need anything else, just check @ R_ 419_ 1769 @ to solve it.

3、 Application examples of reflection mechanism

3.1. Use reflection to store an object of type string in the arryalist set with generic type int

Principle: generics in a collection are only valid in the compiler, but they will expire at run time,

3.2. Use reflection to simplify the number of servlets.

What do you mean? Whenever we write a function, we need to write a corresponding servlet. As a result, there are many servlets that we can't see, so we optimize them in two ways,

        3.2. 1. Pass one parameter from the page each time, method = "XXX"; Then write a servlet, get the value of its parameter method, and judge. If it is add, call the add method. If it is delete, call the delete method. In this way, all functions can be written in a servlet.  

      3.2. 2. Using reflection

Write a baseservlet to inherit httpservlet, which is a general baseservlet. You need to understand the servlet lifecycle

Write the method servlet class of the specific implementation.

        MySerlvet001 extends BaseServlet

Explanation: you need to understand the life cycle of a servlet, that is, the service method. Because it is a servlet, you will pass through the service method when accessing it, but it is not in the subclass myservlet001. Therefore, you can find it in the parent baseservlet, find it, and then obtain the parameters to know what method to call, because the method is written in the subclass, Therefore, through reflection, get the corresponding method in the subclass and run it. Note the usage of this parameter in baseservlet. Need to understand it. To understand our program.

4、 Summary

Reflection is basically finished. In fact, it is to explain some of its APIs. If you don't understand it, you can check the API. Important ideas can be better understood only when they are encountered in practice. Let's go through this first, piecemeal knowledge.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>