Details and examples of Java reflection mechanism

  • 2020-06-15 09:03:40
  • OfStack

Details and examples of Java reflection mechanism

Reflection, at that time often listen to them say, oneself also have seen 1 some data, also may have used in the design pattern, but the feeling did not have a deeper understanding of it, this time restudy 1, the feeling is ok!

1. First, let's look at the concept of reflection:

It mainly refers to the ability that a program can access, detect and modify its own state or behavior, and 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 improperly!

See concept very dizzy, continue to look down.

2. Role of reflection mechanism:

1, decompilation:.class-- > .Java

2. Access the properties, methods and constructors of java objects through reflection mechanism;

This will make it easier to understand 1, so let's look at how to implement these functions.

sun provides us with those classes in the reflection mechanism:


java.lang.Class;    
java.lang.reflect.Constructor; java.lang.reflect.Field;  
java.lang.reflect.Method;
java.lang.reflect.Modifier;

Many of the methods, properties, and other operations in reflection can be queried from these four classes. Or which sentence to learn to keep looking up API, that is our best teacher.

4. Specific function realization:

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


// The first 1 Kind of way:  
Classc1 = Class.forName("Employee"); 
// The first 2 Kind of way:  
//java Each of the types in class  attribute . 
Classc2 = Employee.class; 
 
// The first 3 Kind of way:  
//java In any language 1 a java Object has getClass  methods  
Employeee = new Employee(); 
Classc3 = e.getClass(); //c3 Is a runtime class  (e The runtime class of Employee) 

2, Create object: After getting the class, let's create its object, using newInstance:


Class c =Class.forName("Employee"); 
 
// To create this Class  Object represents a class 1 A new instance  
Objecto = c.newInstance(); // Call the Employee Is a parameterless construction method . 

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

a, first look at the way to get all the attributes:


// Get the entire class  
   Class c = Class.forName("java.lang.Integer"); 
    // Gets all the attributes ? 
   Field[] fs = c.getDeclaredFields(); 
  
     // Defines a variable length string used to store properties  
   StringBuffer sb = new StringBuffer(); 
   // Each property is concatenated into the string by appending  
   // The most out of public define  
   sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{\n"); 
   // The inside of each 1 A property  
   for(Field field:fs){ 
    sb.append("\t");// The blank space  
    sb.append(Modifier.toString(field.getModifiers())+" ");// Gets a modifier for an attribute, for example public . static , etc.  
    sb.append(field.getType().getSimpleName() + " ");// The name of the type of the property  
    sb.append(field.getName()+";\n");// Attribute name + enter  
   } 
  
   sb.append("}"); 
  
   System.out.println(sb); 

b, get specific attributes and learn by comparing the traditional methods:


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"); 
 // To obtain id attribute  
 Field idF = c.getDeclaredField("id"); 
 // Instantiate the class assignment to o 
 Object o = c.newInstance(); 
 // Break the encapsulation  
 idF.setAccessible(true); // Using reflection mechanisms can break encapsulation, resulting in java The properties of the object are not secure.  
 // to o The object's id Attribute assignment "110" 
 idF.set(o, "110"); //set 
 //get 
 System.out.println(idF.get(o)); 
} 

4. Obtain method and constructor without detailed description, just take a look at 1.

[

方法关键字

含义

getDeclaredMethods()

获取所有的方法

getReturnType()

获得方法的放回类型

getParameterTypes()

获得方法的传入参数类型

getDeclaredMethod("方法名",参数类型.class,……)

获得特定的方法

 

 

构造方法关键字

含义

getDeclaredConstructors()

获取所有的构造方法

getDeclaredConstructor(参数类型.class,……)

获取特定的构造方法

 

 

父类和父接口

含义

getSuperclass()

获取某类的父类

getInterfaces()

获取某类实现的接口

]

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

5. Add reflection and configuration files to make our program more flexible:

In the design pattern learning, learning the abstract factory when the use of reflection to more convenient to read the database link string, at that time not too understand, copy. Take a look at the use of reflection + configuration files in NET:

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


 <configuration> 
lt;appSettings> 
<add  key="" value=""/> 
lt;/appSettings> 
  </configuration> 

Reflection:


assembly.load(" The name of the current assembly ").CreateInstance(" The current namespace name ". The name of the class to instantiate ); 

This advantage is very easy to facilitate us to transform the database, for example, we upgrade the system database from SQL Server to Oracle, then we write two D layer, in the configuration file content change 1, or conditional choice 1 can bring great convenience.

Of course, JAVA is actually the same thing, except that the configuration file here is.properties, which is called the properties file. Read it by reflection. This code is fixed, but we can change the content of the configuration file, which makes our code much more flexible!

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

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: