当前位置:网站首页>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;}边栏推荐
- 开发转测试:从0开始的6年自动化之路...
- Drawing shadow error diagram with MATLAB
- Sqoop【付诸实践 02】Sqoop1最新版 全库导入 + 数据过滤 + 字段类型支持 说明及举例代码(query参数及字段类型强制转换)
- Source code analysis of object wait notify notifyAll
- Force deduction brush questions, sum of three numbers
- “互联网+”时代的现代医学
- 挡不住了,纯国产PC已就位,美国的软硬件体系垄断正式被破
- v-premission添加权限
- 【信息系统项目管理师】初见高项系列精华汇总
- QT随手笔记(六)——更新界面、截图、文件对话框
猜你喜欢

R语言ggplot2可视化: 将图例标题(legend title)对齐到ggplot2中图例框的中间(默认左对齐、align legend title to middle of legend)

MySQL的逻辑架构

Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market

高斯消元求解矩阵的逆(gauss)

Qt随手笔记(三)在vs中使用QtCharts画折线图

The diagram of user login verification process is well written!

Fiddler packet capturing tool for mobile packet capturing

matlab中的AR模型短时预测交通流

Fuzzy PID control of motor speed

Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
随机推荐
matlab simulink实现模糊pid对中央空调时延温度控制系统控制
2022年中科磐云——服务器内部信息获取 解析flag
(2) Hand eye calibration of face scanner and manipulator (eye out of hand: nine point calibration)
SSG框架Gatsby访问数据库,并显示到页面上
一种分布式深度学习编程新范式:Global Tensor
matlab中的AR模型短时预测交通流
Global variables in DLL
Learning notes: what are the common array APIs that change the original array or do not change the original array?
m进制数str转n进制数
新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐
IIS网站配置
asp. Net using redis cache
EOJ 2020 1月月赛 E数的变换
音视频知识
【荧光字效果】
js 表格自动循环滚动,鼠标移入暂停
Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market
ie7设置overflow属性失效解决方法
B站这个视频我是跪着看完的
Registration module use case writing