当前位置:网站首页>What is the principle of reflection mechanism?
What is the principle of reflection mechanism?
2022-07-26 09:44:00 【Hua Weiyun】
The second kind :Spring Use of framework , The classic one xml Configuration mode .
Spring adopt XML Configuration mode loading Bean The process of :
Put all the XML or Properties The configuration file is loaded into memory ;
Java Class xml or properties What's in it , Get the bytecode string of the corresponding entity class and the related attribute information ;
Use reflection mechanism , According to this string, get the Class example ;
Dynamic configuration of instance properties .
Spring The advantage of this is :
You don't have to go in the code every time new Or do something else ;
If you want to change it later, change the configuration file directly , Code maintenance is very convenient ;
Sometimes in order to meet certain needs ,Java You don't have to call another method directly in a class , It can be realized by reflection mechanism .
simulation Spring load XML The configuration file :
public class BeanFactory {
private Map<String, Object> beanMap = new HashMap<String, Object>();
/**
* bean Factory initialization .
* @param xml xml The configuration file
*/
public void init(String xml) {
try {
// Read the specified configuration file
SAXReader reader = new SAXReader();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// from class Get the specified xml file
InputStream ins = classLoader.getResourceAsStream(xml);
Document doc = reader.read(ins);
Element root = doc.getRootElement();
Element foo;
// Traverse bean for (Iterator i = root.elementIterator("bean"); i.hasNext();) { foo = (Element) i.next(); // obtain bean Properties of id and class Attribute id = foo.attribute("id"); Attribute cls = foo.attribute("class"); // utilize Java The reflex mechanism , adopt class Get the name of Class object Class bean = Class.forName(cls.getText()); // Get corresponding class Information about java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean); // Get its property description java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); // How to set the value Method mSet = null; // Create an object Object obj = bean.newInstance(); // Traversing this bean Of property attribute for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) { Element foo2 = (Element) ite.next(); // Get the property Of name attribute Attribute name = foo2.attribute("name"); String value = null; // Get the property Child elements value Value for(Iterator ite1 = foo2.elementIterator("value"); ite1.hasNext();) { Element node = (Element) ite1.next(); value = node.getText(); break; } for (int k = 0; k < pd.length; k++) { if (pd[k].getName().equalsIgnoreCase(name.getText())) { mSet = pd[k].getWriteMethod(); // utilize Java Call one of the objects set Method , And set the value in mSet.invoke(obj, value); } } } // Put the object in beanMap in , among key by id value ,value As object beanMap.put(id.getText(), obj); } } catch (Exception e) { System.out.println(e.toString()); } } //other codes
}
What is the principle of reflection mechanism ?
Class actionClass=Class.forName(“MyClass”);
Object action=actionClass.newInstance();
Method method = actionClass.getMethod(“myMethod”,null);
method.invoke(action,null);
The above is an example of the most common use of reflection , The first two lines implement the loading of classes 、 Linking and initialization (newInstance Method is actually called with reflection Method ), The last two lines implement the class Object method Object then performs the reflection call .
Because the principle of reflection is more complicated , The following is a brief description of the process , Little friends who want to know more about , You can read this article :https://www.cnblogs.com/yougewe/p/10125073.html
Reflection gets class instances Class.forName(), No implementation left to java, It was handed over jvm To load the ! The main thing is to get ClassLoader, And then call native Method , pick up information , Loading a class is a callback java.lang.ClassLoader. Last ,jvm There will be a callback ClassLoader Class loading !
newInstance() I did three things :
Authority detection , If you don't throw an exception directly ;
Find a parameterless constructor , And cache it ;
Call the parameterless constructor of a specific method , Generate an instance and return .
obtain Method object ,
above Class Object is loaded by JVM Tectonic ,JVM Manage a unique Class object , This Class The object maintains all the Method,Field,Constructor Of cache, This cache It can also be called the root object .
Every time getMethod Acquired Method Objects hold references to the root object , Because some of the heavyweights Method Member variables of ( Mainly MethodAccessor), We don't want to create Method Objects need to be reinitialized , So one represents all the methods Method Objects share the root object's MethodAccessor, The root object's copy Methods make a copy :
Method copy() {
Method res = new Method(clazz, name, parameterTypes, returnType, exceptionTypes, modifiers, slot, signature, annotations, parameterAnnotations, annotationDefault); res.root = this; res.methodAccessor = methodAccessor; return res;}
边栏推荐
- POJ 1012 Joseph
- Unstoppable, pure domestic PCs have been in place, and the monopoly of the U.S. software and hardware system has been officially broken
- 面试题目大赏
- matlab中的AR模型短时预测交通流
- V-for dynamically sets the SRC of img
- Node memory overflow and V8 garbage collection mechanism
- Neural network and deep learning-6-support vector machine 1-pytorch
- Fiddler packet capturing tool for mobile packet capturing
- B站这个视频我是跪着看完的
- 编写一个在bash / shell 和 PowerShell中均可运行的脚本
猜你喜欢
asp. Net using redis cache
spolicy请求案例
Development to testing: a six-year road to automation starting from 0
R language ggplot2 visualization: align the legend title to the middle of the legend box in ggplot2 (default left alignment, align legend title to middle of legend)
Node 内存溢出及V8垃圾回收机制
uni-app学习总结
2022 zhongkepan cloud - server internal information acquisition and analysis flag
[MySQL database] a collection of basic MySQL operations - the basis of seeing (adding, deleting, modifying, and querying)
2019 ICPC Asia Yinchuan regional (water problem solution)
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
随机推荐
The diagram of user login verification process is well written!
Use of OpenCV class
Neural network and deep learning-6-support vector machine 1-pytorch
The whole process of server environment configuration
v-premission添加权限
Qt随手笔记(二)Edit控件及float,QString转化、
音视频知识
m进制数str转n进制数
antd TreeSelect获取父节点的值
Antd treeselect gets the value of the parent node
Great reward for interview questions
2019 ICPC Asia Yinchuan Regional(水题题解)
Malloc failed to allocate space and did not return null
面试突击68:为什么 TCP 需要 3 次握手?
正则表达式
A new paradigm of distributed deep learning programming: Global tensor
Process32first returns false, error x message 24
Development to testing: a six-year road to automation starting from 0
M-ary number STR to n-ary number
高斯消元