PropertyDescriptor和BeanUtils使用去获得类的get 和 setter访问器

PropertyDescriptor类 的构造器描述为

PropertyDescriptor pd=new PropertyDescriptor(String propertyName, Class<?> beanClass) 
第一个参数是字段名字,第二个参数是类型名称
Method methodGetId = pd.getReadMethod(); 
通过改方法获得到类型的get访问方法
Object retVal = methodGetId.invoke(stu);
通过invoke方法传入类型对象的实例,获取返回的数据

接下来我们看看BeanUtils是如何实现的,
首先BeanUtils是org.springframework:spring-bean下面的类
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(Student.class,"name");
通过getPropertyDescriptor获取PropertyDescriptor对象实列的。看上去好像和new 没有什么区别啊?
别急在调试跟踪源码
@Nullable
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) throws BeansException {
CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz);
return cr.getPropertyDescriptor(propertyName);
}
CachedIntrospectionResults这个类很关键,Cache开头是不是用了缓存吗?通过分析源码发现底层是有用到缓存,
通过内审Introspector
方法缓BeanInfo的信息,还把PropertyDescriptor缓存起来了,加快查找速度
通过分析发下BeanUtils会缓存BeanInfo的信息。

原文地址:https://www.cnblogs.com/TakumiWu/p/12463839.html