Spring basic idea IOC
The second is java reflection. The reflection mechanism is an important implementation core of spring. Today when I looked at spring’s third-level cache to solve the problem of circular references, I discovered the life cycle of a bean. It is highly similar to the generation process of Java objects. Then I went over the bean creation process and found that the process of a bean instance from scratch is very interesting. Spring uses extremely elegant code to realize the use of reflection and various methods. This map data structure realizes the pipeline production of beans, which is very elegant, so I tried to use reflection to write a gadget that reversely generates instance objects.
Then you need to understand the process of generating an object beforehand:
I summarize the object creation process as:
Check whether there is a symbolic reference to the object in the constant pool and determine Whether it has gone through the class loading process, if not, the class loading process will be carried out.
Allocate memory for new objects (two methods: pointer collision and free list
Set the object header.
Object initialization, this is the process of executing your constructor method and assigning the values you want to define to the fields you need.
Add some details: In the process of allocating memory for new objects, first of all, the memory size required by an object after the class loading is completed is completely determined. The process of allocating memory is actually in the Java heap. Divide a memory of equal size to it, but how to divide it? If the memory layout of the Java heap is allocated in a strict order, that is, one side is used and the other side is free, then the memory will be allocated by pointer collision. The so-called pointer is collected at the dividing line between the free area and the used area. When memory is required, the pointer moves backward until the length covered by the move is equal to the memory size required by the java object and stops and allocates. But what if the memory layout of the Java heap is fragmented and discontinuous? We can only maintain a list, which records the size and location information of all Java heap free areas. When allocating, we only need to find the most suitable area allocation for new objects.
The ability of the garbage collector and whether it can perform space compression and sorting determine whether the Java heap is regular. When the collectors we use are Serial and Parnew, they are allocated by pointer collision. When we use the CMS garbage collector, we need to use the troublesome free area table allocation.
Here we focus on filling in the properties and methods: the soul of an object is its properties and methods:
The core properties used by the entire tool:
private static volatile Constructor<?> constructor; private static volatile Object newInstance; private static volatile Map<String, Method> methodMap;
Let’s first look at the functions of these methods:
public static Constructor<?> getConstructor(Object dataType) { Class<?> typeClass = dataType.getClass(); try { Constructor<?> constructor = typeClass.getConstructor(); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { e.printStackTrace(); return null; } }
Get the constructor of the type. Note that this is a no-parameter construct. If you don’t have a no-parameter construct, it is very likely to report an error, because we don’t know either. How many attributes does it have, right? (Always remember that we are reverse engineering!!! We don’t know what is in this type!!! Everything is information brought by reflection)
public static void fillValueToNewInstance(Object dataType, Map<String, Object> initialMap) throws Exception { constructor = getConstructor(dataType); Class<?> typeClass = dataType.getClass(); Field[] declaredFields = typeClass.getDeclaredFields(); Iterator<Field> fieldIterator = Arrays.stream(declaredFields).iterator(); newInstance = constructor.newInstance(); while (fieldIterator.hasNext()) { Field field = fieldIterator.next(); field.setAccessible(true); if (initialMap != null) field.set(newInstance, initialMap.get(field.getName())); } }
Get the attributes and fill in the attribute values, The attributes are also included here.
public static Method[] getMethodArray(Object dataType) { return dataType.getClass().getDeclaredMethods(); }
Get all methods to form a method array.
public static void fillMethodMap(Object dataType) { methodMap = new HashMap<>(); Method[] methodArray = getMethodArray(dataType); Iterator<Method> iterator = Arrays.stream(methodArray).iterator(); while (iterator.hasNext()) { Method method = iterator.next(); method.setAccessible(true); methodMap.put(method.getName(), method); } }
Save the method into the method collection for storage.
public static Object useMethod(String methodName, @Nullable Object... parameters) throws Exception { return methodMap.get(methodName).invoke(newInstance, parameters); }
The method of use is to pass the name.
@SneakyThrows public static Object getBean(Object dataType, Map<String, Object> parameterMap) { fillValueToNewInstance(dataType, parameterMap); fillMethodMap(dataType); return newInstance; }
getBean method.
public static void main(String[] args) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("name","xu"); map.put("age",Integer.valueOf(18)); map.put("sex",'女'); Person bean = (Person) getBean(new Person(), map); System.out.println(bean.toString()); System.out.println(useMethod("toString")); }
Test method. The type information is as follows:
class Person { private String name; private Integer age; private Character sex; //无参构造绝对不能少 public Person() { } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", sex=" + sex + '}'; } }
The test results are as follows:
Here we do not use Person person = new Person(); to instantiate the object, use Reflection implements the instantiation of objects.
I will list the reflection methods used in it:
getDeclaredFields Get the domain attribute object
getName Get the attribute name
getType Get the word of the attribute type Section code file
setAccessible(true) Set brute force cracking and obtain the use of private attributes
getDeclaredMethods Get all method arrays
getClass Get bytecode file
getConstructor Get the parameterless constructor
The above is the detailed content of How SpringBoot uses reflection to simulate IOC and getBean. For more information, please follow other related articles on the PHP Chinese website!