相关类介绍
在 Java 中,可通过 java.beans 包下的相关类,来获取一个类中属性的描述信息,常用的方法如下:
public class SimpleTest {
public static void main(String[] args) throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(NameMatchMethodPointcutAdvisor.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
System.out.println(beanInfo.getClass().getName());
for (PropertyDescriptor pd : propertyDescriptors) {
System.out.println(pd.getName());
}
System.out.println("*************************");
for (PropertyDescriptor pd : propertyDescriptors) {
Method writeMethod = pd.getWriteMethod();
Method readMethod = pd.getReadMethod();
if (writeMethod != null) {
System.out.println("write method: " + writeMethod.getName());
}
if (readMethod != null) {
System.out.println("read method: " + readMethod.getName());
}
}
}
}
执行后,发现获取的 beanInfo 类型是 java.beans.GenericBeanInfo,并且会获得相应的读写方法。
下面看看判断示例:
public static boolean isWritableProperty(Class<?> clazz, String propertyName) throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : propertyDescriptors) {
if (propertyName.equals(pd.getName()) && pd.getWriteMethod() != null) {
return true;
}
}
return false;
}
这样,就可以判断给定的属性在这个类中是否可写。
使用案例
在 spring 中,对创建的半成品对象进行属性填充时,会判断这个配置的属性在这个给定类中是否可写。
@Override
public boolean isWritableProperty(String propertyName) {
try {
PropertyHandler ph = getPropertyHandler(propertyName);
if (ph != null) {
return ph.isWritable();
}
else {
// Maybe an indexed/mapped property...
getPropertyValue(propertyName);
return true;
}
}
catch (InvalidPropertyException ex) {
// Cannot be evaluated, so can't be writable.
}
return false;
}
以上代码来自 BeanWrapperImpl 的父类 AbstractNestablePropertyAccessor,核心判断就是前面的判断示例所实现的那样。