1:简单说明
正如其名称,用于描述属性相关的信息,如对于读写方法的设置和读取,获取属性的类型等操作。
2:源码
2.1:public构造方法
public PropertyDescriptor(String propertyName, // 属性的名称
Class<?> beanClass // bean的class类型
)
public PropertyDescriptor(String propertyName, // 属性名称
Class<?> beanClass, // bean的class类型
String readMethodName, // 读方法名称
String writeMethodName // 写方法名称
)
public PropertyDescriptor(String propertyName, // 属性名称
Method readMethod, // 读方法
Method writeMethod // 写方法
)
2.2:主要方法
// 获取属性的类型
public synchronized Class<?> getPropertyType() {}
// 获取读方法
public synchronized Method getReadMethod() {}
// 设置读方法
public synchronized void setReadMethod(Method readMethod) {}
// 获取读方法
public synchronized Method getWriteMethod() {}
// 设置读方法
public synchronized void setWriteMethod(Method writeMethod){}
// 设置属性可以使用的属性编辑器类型
public void setPropertyEditorClass(Class<?> propertyEditorClass) {}
// 获取当前设置的属性编辑器类型
public Class<?> getPropertyEditorClass() {}
// 创建bean对象对当前属性的属性编辑器
public PropertyEditor createPropertyEditor(Object bean) {}
3:例子
3.1:自定义属性编辑器
/**
* 自定义的属性编辑器,转换数据类型
*/
public class MyAgePropertyEditor extends PropertyEditorSupport {
private String sourceText;
/**
* 设置源数据值
* @param text
* @throws IllegalArgumentException
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
this.sourceText = text;
}
/**
* 转换为满足age属性要求的int类型
* @return
*/
@Override
public Object getValue() {
return Integer.valueOf(sourceText);
}
}
3.2:定义bean
public class BeanForPropertyDescriptor {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.3:测试代码
public class MainForPropertyDescriptor {
public static void main(String[] args) throws Exception {
Class<BeanForPropertyDescriptor> beanForPropertyDescriptorClass
= BeanForPropertyDescriptor.class;
PropertyDescriptor agePropDescriptor
= new PropertyDescriptor("age", beanForPropertyDescriptorClass);
Method readMethod = agePropDescriptor.getReadMethod();
System.out.println("读方法是:");
System.out.println(readMethod);
Method writeMethod = agePropDescriptor.getWriteMethod();
System.out.println("写方法是:");
System.out.println(writeMethod);
// 设置属性编辑器,用来修改属性
agePropDescriptor.setPropertyEditorClass(MyAgePropertyEditor.class);
BeanForPropertyDescriptor beanForPropertyDescriptor = new BeanForPropertyDescriptor();
PropertyEditor agePropertyEditor = agePropDescriptor.createPropertyEditor(beanForPropertyDescriptor);
agePropertyEditor.setAsText("90");
Object value = agePropertyEditor.getValue();
System.out.println(value.getClass());
}
}
运行:
读方法是:
public int yudaosourcecode.propertydescriptortest.BeanForPropertyDescriptor.getAge()
写方法是:
public void yudaosourcecode.propertydescriptortest.BeanForPropertyDescriptor.setAge(int)
class java.lang.Integer
Process finished with exit code 0
版权声明:本文为wang0907原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。