This paper analyzes the JAVA reflection mechanism in an example. Share it for your reference, as follows:
Reflection, I often heard them say that I had read some materials and might have used them in the design pattern, but I felt that I didn’t have a deeper understanding of it. I learned it again this time and it felt okay!
1. Let’s take a look at the concept of reflection:
It mainly refers to a ability that a program can access, detect and modify its own state or behavior, and can adjust or modify the state and related semantics of the application described behavior based on the state and results of its own behavior.
Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled when running without having to link source code between components. But improper use of reflection will be very costly!
It's dizzy to see the concept, keep reading.
2. The role of the reflection mechanism:
1. Decompile: .class-->.java
2. Access the properties, methods, constructors, etc. of java objects through reflection mechanism;
This seems easier to understand. Let's take a closer look at how to implement these functions.
3. Let’s first look at the classes sun provides us with the reflection mechanism:
java.lang.Class;java.lang.reflect.Constructor; java.lang.reflect.Field;java.lang.reflect.Method;java.lang.reflect.Modifier;
We can query many methods, attributes and other operations in reflection from these four classes. Or do you need to learn to constantly query the API? That is our best teacher.
4. Specific functions implementation:
1. There are three ways to obtain the class by reflection mechanism. Let’s get the Employee type
//The first method: Classc1 = Class.forName("Employee"); //The second method: //Every type in java has a class attribute. Classc2 = Employee.class; //The third method: //Any java object in the java language has a getClass method Employee = new Employee(); Classc3 = e.getClass(); //c3 is the runtime class (e's runtime class is Employee)2. Create an object: After obtaining the class, we will create its object and use newInstance:
Class c =Class.forName("Employee");//Create a new instance of the class represented by this Class object Objecto = c.newInstance(); //Calling the parameterless constructor of Employee.3. Get attributes: divided into all attributes and specified attributes:
①. First look at the writing method of obtaining all attributes:
//Get the entire class Class c = Class.forName("java.lang.Integer");//Get all attributes?Field[] fs = c.getDeclaredFields();//Define variable-length string, use to store the attribute StringBuffer sb = new StringBuffer();//Split each attribute into this string by appending method//The outermost public definition sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{/n");//Each property inside for(Field field:fs){ sb.append("/t");//Space sb.append(Modifier .toString(field.getModifiers())+" ");//Get the modifiers of the attribute, such as public, static, etc. sb.append(field.getType().getSimpleName() + " ");//Get the attribute's Type name sb.append(field.getName()+";/n");//Property name + Enter}sb.append("}");System.out.println(sb);②. Obtain specific attributes and compare traditional methods to learn:
public static void main(String[] args) throws Exception{ <span style="white-space:pre"> </span>//Previous ways: /* User u = new User(); u.age = 12 ; //set System.out.println(u.age); //get */ //get class Class c = Class.forName("User"); //get id attribute Field idF = c.getDeclaredField("id "); //Instantiate this class to o Object o = c.newInstance(); //Breaking the encapsulation idF.setAccessible(true); //Using the reflection mechanism can break the encapsulation, resulting in insecure properties of java objects . //Assign the value "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 construction methods, no longer describe in detail, just look at the keywords:
Method keywords
meaning
getDeclaredMethods()
Get all methods
getReturnType()
Get the return type of method
getParameterTypes()
Obtain the incoming parameter type of the method
getDeclaredMethod("Method Name", parameter type.class,...)
Get a specific method
Constructor keywords
meaning
getDeclaredConstructors()
Get all constructors
getDeclaredConstructor(parameter type.class,...)
Get a specific constructor
Parent class and parent interface
meaning
getSuperclass()
Get the parent class of a certain class
getInterfaces()
Obtain an interface for a certain type of implementation
In this way, we can get various contents of the class and decompile it. For a language like JAVA that compiles first and then runs, the reflection mechanism can make the code more flexible and easier to implement object-oriented.
5. Reflection plus configuration files make our program more flexible:
In the study of design patterns, when learning abstract factories, reflection is used to more conveniently read database link strings, etc., so I didn’t understand it very much at that time, so I copied it accordingly. Take a look at the use of reflection + configuration files in .NET:
The configuration file used at that time was the app.config file, and the content was in XML format, and the contents of the linked database were filled in:
<configuration><appSettings><add key="" value=""/></appSettings></configuration>
How to write reflection:
assembly.load("The name of the current assembly").CreateInstance("The name of the current namespace". The class name to be instantiated);
This advantage is that it is easy to facilitate us to transform the database. For example, if we upgrade the system's database from SQL Server to Oracle, then we will write two D-layers, change the content of the configuration file, or add conditions to select it. It's very convenient.
Of course, the same is true in JAVA, except that the configuration file here is .properties, called the property file. Read the contents in it through reflection. This way the code is fixed, but we can change the content of the configuration file, which makes our code much more flexible!
To sum up, learning JAVA reflection again and using it flexibly can make our code more flexible, but it also has its disadvantages, that is, using it will reduce the performance of our software and increase the complexity, so we also need to Use it carefully.
I hope this article will be helpful to everyone's Java programming.