An example of JAVA reflection mechanism

  • 2020-04-01 04:20:49
  • OfStack

This article illustrates the JAVA reflection mechanism. Share with you for your reference, as follows:

Reflection, at that time, I often heard them say, I have seen some materials, may also be used in the design mode, but I feel it does not have a deeper understanding of it, this time to learn again, feel ok!

First, take a look at the concept of reflection:

Mainly refers to the ability of a program to access, detect and modify its own state or behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and results of its own behavior.
Reflection is a powerful tool in Java that makes it easy to create flexible code that can be assembled at runtime without having to link source code between components. But reflection can be costly if used incorrectly!
It's a very confusing concept. Keep going.

Ii. Function of reflection mechanism

1. Decompilation:. Class --> .java
2. Access the properties, methods and constructors of Java objects through reflection mechanism;
It's a little bit easier to understand, but let's look at how to do that.

Third, let's take a look at the classes in the reflection mechanism provided by sun:

java.lang.reflect.Constructor; java.lang.reflect.Field;

There are a lot of reflection methods and properties that we can look up from these four classes. Or which sentence to learn to constantly query API, that is our best teacher.

Iv. Specific function realization:

1. There are three methods to get the class by reflection mechanism. Let's get the Employee type

//The first way:
Classc1 = Class.forName("Employee"); 
//The second way:
//Every type in Java has a class attribute.
Classc2 = Employee.class; 
//The third way:
//Any Java object in the Java language has a getClass method
Employeee = new Employee(); 
Classc3 = e.getClass(); //c3 Is a runtime class  (e The runtime class is Employee)

2. Create object: after obtaining the class, we will create its object, using newInstance:

Class c =Class.forName("Employee");
//Creates a new instance of the Class represented by this Class object
Objecto = c.newInstance(); //The parameterless constructor for Employee is called.

3. Get attributes: divided into all attributes and specified attributes:

First look at the way to get all the attributes:

//Get the entire class
Class c = Class.forName("java.lang.Integer");
//Get all the attributes ?
Field[] fs = c.getDeclaredFields();
//Defines a variable-length string to store properties
StringBuffer sb = new StringBuffer();
//Each attribute is concatenated into this string by appending
//The outermost public definition
sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{n");
//Every property inside
for(Field field:fs){
    sb.append("t");//The blank space
    sb.append(Modifier.toString(field.getModifiers())+" ");//Get modifiers for properties, such as public, static, and so on
    sb.append(field.getType().getSimpleName() + " ");//The name of the type of the attribute
    sb.append(field.getName()+";n");//Property name + enter

(2) get specific attributes, compared to the traditional method to learn:

public static void main(String[] args) throws Exception{ 
<span style="white-space:pre"> </span>//The old way:
  User u = new User(); 
  u.age = 12; //set 
  System.out.println(u.age); //get 
  //For class
  Class c = Class.forName("User"); 
  //Get id attribute
  Field idF = c.getDeclaredField("id"); 
  //Instantiate this class to o
  Object o = c.newInstance(); 
  //Break the encapsulation
  idF.setAccessible(true); //The use of reflection breaks encapsulation, resulting in unsafe properties for Java objects.
  //Assign "110" to the id attribute of o object
  idF.set(o, "110"); //set 

4. Get method and construction method, no longer describe in detail, just look at the keywords:

Method keyword



Get all the methods


Gets the return type of the method


Gets the incoming parameter type of the method

getDeclaredMethod(" The method name ", The parameter types .class, ... )

Get specific methods



Constructor keyword



Gets all the constructors

getDeclaredConstructor( The parameter types .class, ... )

Gets the specific constructor



Parent class and parent interface



Gets the parent of a class


Gets the interface for some class of implementation


So we can get the various contents of the class, decompiled. For a compile-and-run language like JAVA, reflection makes code more flexible and object oriented.

5. Reflection and configuration files make our program more flexible:

In the design pattern learning, when learning the abstract factory, we used reflection to read the database link string more conveniently. At that time, we did not understand it, so we copied it. Take a look at the use of reflection + configuration files

At that time, the configuration file used was app.config file, and the content was in XML format. The contents of the linked database were filled in:

<add key="" value=""/>

How to write reflection:

Assembly. Load (" name of current assembly ").CreateInstance(" current namespace name ". Class name to instantiate).  

The advantage of this is that it is easy for us to change the database, for example, we will upgrade the system database from SQL Server to Oracle, so we write two D layer, in the configuration file content to change, or add conditions to choose, bring a great convenience.

Of course, the same is true in JAVA, except that the configuration file here, called a properties file. The contents are read by reflection. This code is fixed, but we can change the contents of the configuration file, which makes our code a lot more flexible!

To sum up, JAVA reflection relearning, flexible use of it, can make our code more flexible, but it also has its disadvantages, is to use it will reduce the performance of our software, increase the complexity, so we need to use it carefully.

I hope this article has been helpful to you in Java programming.

Related articles: