当前位置:网站首页>反射机制的原理是什么?
反射机制的原理是什么?
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;}边栏推荐
- 微信小程序AvatarCropper 头像裁剪
- 小白搞一波深拷贝 浅拷贝
- 如何添加一个PDB
- Learning notes: what are the common array APIs that change the original array or do not change the original array?
- How to add a PDB
- dll中的全局变量
- (2) Hand eye calibration of face scanner and manipulator (eye out of hand: nine point calibration)
- Antd treeselect gets the value of the parent node
- 官方颁发的SSL证书与自签名证书结合实现网站双向认证
- Mo team learning summary (II)
猜你喜欢
随机推荐
莫队学习总结(二)
Smart gourmet C language
Interpretation of the standard of software programming level examination for teenagers_ second level
Learning notes: what are the common array APIs that change the original array or do not change the original array?
[Online deadlock analysis] by index_ Deadlock event caused by merge
解决ProxyError: Conda cannot proceed due to an error in your proxy configuration.
2021年山东省中职组“网络空间安全”B模块windows渗透(解析)
新公链Aptos何以拉满市场期待值?
【Mysql数据库】mysql基本操作集锦-看得会的基础(增删改查)
ie7设置overflow属性失效解决方法
Gauss elimination
Registration module use case writing
音视频知识
v-premission添加权限
malloc分配空间失败,并且不返回null
学习笔记之常用数组api 改变原数组和不改变原数组的有哪些?
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
Neural network and deep learning-6-support vector machine 1-pytorch
copyTo
注册模块用例编写








