Reflection mechanism in Java and Java reflection mechanism
Notes for learning Java !!!
If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group with the group number 618528494.Let's learn Java together!
Reflection: At that time, I often heard them say that I have read some materials and may have used them in the design mode. But I feel that I don't have a deep understanding of it. I learned it again this time, it feels okay!
First, let's take a look at the concept of reflection:
It mainly refers to the ability of a program to access, detect, and modify its own state or behavior, and according to the status and results of its own behavior, adjusts or modifies the status and semantics of the behavior described by the application.
Reflection is a powerful tool in Java that allows us to easily create flexible Code. The Code can run the configuration again without the need for source code links between components. However, improper reflection is costly!
Look at the concept is dizzy, continue to look down.
Ii. Functions of the reflection mechanism:
1. decompilation:. class -->. java
2. Access the attributes, methods, and constructor of the java object through the reflection mechanism;
This seems easier to understand. Let's take a look at how to implement these functions.
Iii. Here, let's take a look at the classes in which sun provides us with reflection mechanisms:
Java. lang. Class;
Java. lang. reflect. Constructor; java. lang. reflect. Field;
Java. lang. reflect. Method;
Java. lang. reflect. Modifier;
Many operations such as methods and attributes in reflection can be queried from these four classes. Which of the following statements should we learn to constantly query APIs? That is our best teacher.
4. Specific functions:
1. There are three methods for obtaining the reflection mechanism class. Let's get the Employee type.
[Java]View plain copy print?
- // Method 1:
- Classc1 = Class. forName ("Employee ");
- // Method 2:
- // In java, each type has the class attribute.
- Classc2 = Employee. class;
- // Method 3:
- // Any java object in java has the getClass method.
- Employeee = new Employee ();
- Classc3 = e. getClass (); // c3 is the runtime class (e's runtime class is the Employee)
2. Create an object: Obtain the object of the class and use newInstance:
[Java]View plain copy print?
- Class c = Class. forName ("Employee ");
- // Create a new instance of the Class represented by this Class Object
- Objecto = c. newInstance (); // call the parameter-free constructor of Employee.
3. Get attributes: All attributes and specified attributes:
A. Let's first look at how to get all the attributes:
[Java]View plain copy print?
- // Obtain the entire class
- Class c = Class. forName ("java. lang. Integer ");
- // Obtain all attributes?
- Field [] fs = c. getDeclaredFields ();
- // Defines a variable-length string for storing attributes
- StringBuffer sb = new StringBuffer ();
- // Concatenate each attribute to this string using the append method.
- // Public definition of the outermost side
- Sb. append (Modifier. toString (c. getModifiers () + "class" + c. getSimpleName () + "{\ n ");
- // Each attribute in it
- For (Field field: fs ){
- Sb. append ("\ t"); // Space
- Sb. append (Modifier. toString (field. getModifiers () + ""); // get attribute modifiers, such as public and static.
- Sb. append (field. getType (). getSimpleName () + ""); // name of the attribute type
- Sb. append (field. getName () + "; \ n"); // attribute name + press ENTER
- }
- Sb. append ("}");
- System. out. println (sb );
B. Get specific attributes and learn from the traditional methods:
[Java]View plain copy print?
- Public static void main (String [] args) throws Exception {
- <Span style = "white-space: pre"> </span> // previous method:
- /*
- User u = new User ();
- U. age = 12; // set
- System. out. println (u. age); // get
- */
- // Obtain the class
- Class c = Class. forName ("User ");
- // Obtain the id attribute
- Field idF = c. getDeclaredField ("id ");
- // Instantiate this class to o
- Object o = c. newInstance ();
- // Break the Encapsulation
- IdF. setAccessible (true); // The reflection mechanism can be used to break the encapsulation, leading to insecure attributes of java objects.
- // Assign "110" to the id attribute of the o object"
- IdF. set (o, "110"); // set
- // Get
- System. out. println (idF. get (o ));
- }
4. Get methods and constructor methods. I will not describe them in detail. Just look at the keywords:
Method keywords |
Description |
GetDeclaredMethods () |
Get all methods |
GetReturnType () |
Obtain the method replacement type |
GetParameterTypes () |
Obtain the input parameter type of the method. |
GetDeclaredMethod ("method name", parameter type. class ,......) |
Obtain a specific method |
|
|
Constructor keywords |
Description |
GetDeclaredConstructors () |
Obtain all constructor Methods |
GetDeclaredConstructor (parameter type. class ,......) |
Obtain a specific Constructor |
|
|
Parent class and parent interface |
Description |
GetSuperclass () |
Obtain a class of parent class |
GetInterfaces () |
Obtain an implemented Interface |
In this way, we can obtain various contents of the class and decompile them. For JAVA, a language that requires compilation and execution, the reflection mechanism can make the code more flexible and easier to implement object-oriented.
5. Reflection and configuration files make our programs more flexible:
During the design model learning, reflection was used to read database link strings more easily when learning abstract factories. At that time, I did not understand it too well and copied it. Let's take a look at the use of reflection + configuration files in. NET:
The configuration file used at that time is the app. config file in XML format. Enter the content of the Linked database in it:
[Html]View plain copy print?
- <Configuration>
- Lt; deleetask>
- <Add key = "" value = ""/>
- Lt;/appSettings>
- </Configuration>
Reflection statement:
[Csharp]View plain copy print?
- Assembly. load ("current assembly name"). CreateInstance ("Current namespace name". Name of the class to be instantiated );
The advantage is that we can easily change the database. For example, if we upgrade the system database from SQL Server to Oracle, We will write two copies of layer D, you can change the content of the configuration file, or select the configuration file by adding conditions, which makes it very convenient.
Of course, the same is true in JAVA, except that the configuration file is. properties, which is called an attribute file. Read the content through reflection. In this way, the code is fixed, but the content of the configuration file can be changed, which makes our code much more flexible!
In summary, the re-learning and flexible use of JAVA reflection can make our code more flexible, but it also has its shortcomings, it will reduce the performance and complexity of our software, so we need to use it with caution.
Notes for learning Java !!!
If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group with the group number 618528494.Let's learn Java together!