Talking about the reflection mechanism of java is only helpful to understand this mechanism.

First of all, when understanding reflection in java , we should ask a few questions first,

First, what is the reflection mechanism of java?

Second, what is the function of java reflection mechanism?

Third, why use the reflection mechanism of java?

Fourth, how is the reflection mechanism of java implemented, and what does the implementation process look like?

Through these four questions, we have a little understanding of the reflection mechanism of java.

first question:

Java's reflection mechanism is in the running state. For any class, it can know all the properties and methods of this class, and any object can call any of its methods and properties. This dynamic call to obtain information and dynamically call the method function of the object is the reflection mechanism of the java language. In other words, it is to load a class that is only known at runtime and its complete internal structure. Take a small chestnut.

package com.sohu.action;


public class TestModel {


	String name="I am a member variable!";
	/**
	 * Constructor
	 */
	public TestModel(){
		System.out.println("----I am the constructor!----");
	}
	/**
	 * static code block
	 */
	static{
		System.out.println("---I am a static code block-----");
	}
	
	{
		System.out.println("----I am a non-static code block----");
	}
	public void method(){
		System.out.println("---I am a local method---");
	}
}


Write the test class:

public class Test3 {


	public static void main(String[] args) {
		try {
			//Test class name.class
			Class testModel=TestModel.class;
			System.out.println("Get package name ===>"+testModel.getPackage());
			System.out.println("Get the full path of the class ===>"+testModel.getName());
			System.out.println("Get class name ===>"+testModel.getSimpleName());
			Method[] methods = testModel.getMethods();
			for(Method method:methods){
				System.out.println("===Get method===="+method.getName());
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
}


The above output is as follows:

Get package name ===>package com.sohu.action
Get the full path of the class ===>com.sohu.action.TestModel
Get class name ===>TestModel
===Get method====method
===Get method====wait
===Get method====wait
===Get method====wait
===Get method====hashCode
===Get method====getClass
===Get method====equals
===Get method====toString
===Get method====notify
===Get method====notifyAll


Here (class name).class is reflection. There are two ways to get the Class object here: new (class).getClass() and Class.forName("full path of the class"), which will be discussed in detail later.

From the above example, we can see that the reflection mechanism of java can obtain the methods and properties of the class that are only known at runtime, and you can do other tests yourself. Now for the
second question:

Features provided by java reflection:

1. Determine the class to which any object belongs at runtime;

2. Build an object of any class at runtime;

3. Determine the member variables and methods of any class at runtime;

4. Call a method of any object at runtime;

The above four are understood with reference to the above example; it should be noted that these four are carried out at runtime rather than compile time, that is to say, we do not know which class is at runtime, and achieve what we want through reflection.
5. Generate dynamic proxy.

Then let's see why we use the reflection mechanism;

First of all, Java's reflection can make the code more flexible and easier to implement object-oriented.

The stage is that java reflection can be decoupled.

For the last question, let's use a simple example to illustrate. The reflection mechanism of java can only play a certain role in understanding, and it needs more effort to understand in depth.

For example, in such a situation, we have multiple entity classes, and the attributes in each entity class are different and will not be repeated. We want to obtain some of the attributes. These attributes are not in the same entity class. How to implement it . code directly

package com.sohu.action;

import java.lang.reflect.Method;
import java.util.List;


/**
 * Encapsulate the method of the union entity class
 * Use java's reflection class method
 * @author HBL1
 *
 */
public class ModelUtils {
	
	//Need a List to place the entity class
	List<Object> list=null;
	
	
	/**
	 * Constructor, assigning
	 * @param list
	 */
	public ModelUtils(List<Object> list){
		this.list=list;
	}

	/**
	 * Get the value of the property
	 * @param fName Get the name of the property of the federated entity class
	 * @return
	 */
	public <T> T getValue(String fName){
		//Assemble the method name, this step is to pass the parameters directly when calling this method, no need to pass the method name
		String methodName="get"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		//Get the entity class where the method name is located
		for(Object o:list){
			try {
				//Look for the method, look for another method without parameters, if only the method can be passed, try to pass it as much as possible to improve the reflection efficiency
				Method method = o.getClass().getMethod(methodName);
				//Check if the method exists
				if(method!=null){
					//Because invoke returns Object type, it needs to be cast to T type
					return (T)method.invoke(o);
				}				
			} catch (Exception e) {
			}
		}
		return null;
	}

	public <T> void setValue(String fName,T value,Class<T> type){
		String methodName="set"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		for(Object o:list){
			try {
				//find method
				Method method = o.getClass().getMethod(methodName,type);
				if(method!=null){
					method.invoke(o, value);
					return;
				}
			} catch (Exception e) {
			}
		}
	}
}
Then we test how the class encapsulated by reflection achieves what we want, and the entity class will not be uploaded here.

package com.sohu.action;

import java.util.ArrayList;
import java.util.List;

import utils.system;
import flex.cc.baseInfo.model.GBankaccount;
import flex.cc.baseInfo.model.GInsurer;

public class Test2 {

	public static void main(String[] args) {
		List<Object> list =new ArrayList<Object>();
		list.add(new GBankaccount());
		list.add(new GInsurer());
		FieldsUtils fieldsUtils=new FieldsUtils(list);
		String name="fparentid";//This is the attribute value you want to get
		String value="I am test data";
		fieldsUtils.setValue(name, value);
		System.out.println(fieldsUtils.getValue(name));
	}
}

The result printed is as follows:

I am test data
Get the data we want.

For java reflection is still in the further understanding, there are many shortcomings, please give more advice,








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325592360&siteId=291194637