当前位置:网站首页>反射机制的原理是什么?
反射机制的原理是什么?
2022-07-26 09:40:00 【华为云】
第二种:Spring 框架的使用,最经典的就是xml的配置模式。
Spring 通过 XML 配置模式装载 Bean 的过程:
将程序内所有 XML 或 Properties 配置文件加载入内存中;
Java类里面解析xml或properties里面的内容,得到对应实体类的字节码字符串以及相关的属性信息;
使用反射机制,根据这个字符串获得某个类的Class实例;
动态配置实例的属性。
Spring这样做的好处是:
不用每一次都要在代码里面去new或者做其他的事情;
以后要改的话直接改配置文件,代码维护起来就很方便了;
有时为了适应某些需求,Java类里面不一定能直接调用另外的方法,可以通过反射机制来实现。
模拟 Spring 加载 XML 配置文件:
public class BeanFactory {
private Map<String, Object> beanMap = new HashMap<String, Object>();
/**
* bean工厂的初始化.
* @param xml xml配置文件
*/
public void init(String xml) {
try {
//读取指定的配置文件
SAXReader reader = new SAXReader();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//从class目录下获取指定的xml文件
InputStream ins = classLoader.getResourceAsStream(xml);
Document doc = reader.read(ins);
Element root = doc.getRootElement();
Element foo;
//遍历bean for (Iterator i = root.elementIterator("bean"); i.hasNext();) { foo = (Element) i.next(); //获取bean的属性id和class Attribute id = foo.attribute("id"); Attribute cls = foo.attribute("class"); //利用Java反射机制,通过class的名称获取Class对象 Class bean = Class.forName(cls.getText()); //获取对应class的信息 java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean); //获取其属性描述 java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); //设置值的方法 Method mSet = null; //创建一个对象 Object obj = bean.newInstance(); //遍历该bean的property属性 for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) { Element foo2 = (Element) ite.next(); //获取该property的name属性 Attribute name = foo2.attribute("name"); String value = null; //获取该property的子元素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(); //利用Java的反射极致调用对象的某个set方法,并将值设置进去 mSet.invoke(obj, value); } } } //将对象放入beanMap中,其中key为id值,value为对象 beanMap.put(id.getText(), obj); } } catch (Exception e) { System.out.println(e.toString()); } } //other codes
}
反射机制的原理是什么?
Class actionClass=Class.forName(“MyClass”);
Object action=actionClass.newInstance();
Method method = actionClass.getMethod(“myMethod”,null);
method.invoke(action,null);
上面就是最常见的反射使用的例子,前两行实现了类的装载、链接和初始化(newInstance方法实际上也是使用反射调用了 方法),后两行实现了从class对象中获取到method对象然后执行反射调用。
因反射原理较复杂,下面简要描述下流程,想要详细了解的小伙伴,可以看这篇文章:https://www.cnblogs.com/yougewe/p/10125073.html
反射获取类实例 Class.forName(),并没有将实现留给了java,而是交给了jvm去加载!主要是先获取 ClassLoader, 然后调用 native 方法,获取信息,加载类则是回调 java.lang.ClassLoader。最后,jvm又会回调 ClassLoader 进类加载!
newInstance() 主要做了三件事:
权限检测,如果不通过直接抛出异常;
查找无参构造器,并将其缓存起来;
调用具体方法的无参构造方法,生成实例并返回。
获取Method对象,
上面的Class对象是在加载类时由JVM构造的,JVM为每个类管理一个独一无二的Class对象,这份Class对象里维护着该类的所有Method,Field,Constructor的cache,这份cache也可以被称作根对象。
每次getMethod获取到的Method对象都持有对根对象的引用,因为一些重量级的Method的成员变量(主要是MethodAccessor),我们不希望每次创建Method对象都要重新初始化,于是所有代表同一个方法的Method对象都共享着根对象的MethodAccessor,每一次创建都会调用根对象的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;}
边栏推荐
- OpenCV 表格识别之表格提取(二)
- 学习笔记之常用数组api 改变原数组和不改变原数组的有哪些?
- (1) Hand eye calibration of face scanner and manipulator (eye on hand)
- JS continuous assignment operation
- v-for动态设置img的src
- Process32first returns false, error x message 24
- IIS网站配置
- Qt随手笔记(三)在vs中使用QtCharts画折线图
- Qt随手笔记(二)Edit控件及float,QString转化、
- The problem of accessing certsrv after configuring ADCs
猜你喜欢
2019 ICPC Asia Yinchuan Regional(水题题解)
Logical architecture of MySQL
开发转测试:从0开始的6年自动化之路...
Fiddler下载安装
The problem of accessing certsrv after configuring ADCs
Drawing shadow error diagram with MATLAB
[Online deadlock analysis] by index_ Deadlock event caused by merge
Redis sentinel mode setup under Windows
高斯消元
v-premission添加权限
随机推荐
Force deduction brush questions, sum of three numbers
Antd treeselect gets the value of the parent node
(二)面扫描仪与机械臂的手眼标定(眼在手外:九点标定)
Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
Mo team learning summary (II)
The combination of officially issued SSL certificate and self signed certificate realizes website two-way authentication
MFC handy notes
面试题目大赏
Process32First返回false,错误x信息24
图解用户登录验证流程,写得太好了!
Xiaobai makes a wave of deep copy and shallow copy
登录模块用例编写
微信小程序AvatarCropper 头像裁剪
Interview shock 68: why does TCP need three handshakes?
微信小程序图片无法显示时显示默认图片
Windows下Redis哨兵模式搭建
电机转速模糊pid控制
Gauss elimination for solving XOR linear equations
(一)面扫描仪与机械臂的手眼标定(眼在手上)
V-permission add permission