PropertyDescriptor
在看 Spring 源码 AbstractAutowireCapableBeanFactory 类时发现很多方法都用到 PropertyDescriptor 这个类,刚开始以为这是 Spring 封装的一个工具类,仔细研究了一番,才发现原来是 JDK 提供的一个操作简单 java bean 的工具类。
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set<String> result = new TreeSet<String>();
PropertyValues pvs = mbd.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
}
那 PropertyDescriptor 到底是干嘛的呢?
简单点说就是 通过 PropertyDescriptor 反射获取属性的 getter/setter 方法
看下面这个案例:
public class PropertyDescriptorTest {
@Test
public void test() throws IntrospectionException, InvocationTargetException, IllegalAccessException {
User user = new User();
//1. 获取 User 类 name 属性的 PropertyDescriptor,用于操作该属性的 set/get 方法
PropertyDescriptor pd = new PropertyDescriptor("name", User.class);
//2. 操作 name 属性的 set 方法
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(user, "binarylei");
//3. 操作 name 属性的 get 方法
Method readMethod = pd.getReadMethod();
String name = (String) readMethod.invoke(user);
System.out.println(name);
}
}
// 准备一个 java bean
public class User {
private String name;
private String password;
// 省略 get/set
}
注: PropertyDescriptor 避免使用拼装方法名,反射获取 Method 对象。
是不是很简单呢?