一、软件包 java.beans
包含与开发 beans 有关的类
二、PropertyDescriptor
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
Java JDK中提供了一套API用来访问某个属性的getter/setter方法,这就是内省
构造方法:
PropertyDescriptor(String propertyName, Class<?> beanClass)
PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName)
PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod)
常用方法:
public class PropertyDescriptor extends FeatureDescriptor
{
//构造方法
//通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个 PropertyDescriptor
public PropertyDescriptor(String propertyName,
Class<?> beanClass)
throws IntrospectionException{}
//获得属性的 Class 对象
public Class<?> getPropertyType(){}
//获得应该用于读取属性值的方法
public Method getReadMethod(){}
//获得应该用于写入属性值的方法
public Method getWriteMethod(){}
使用
public static Object myObjectMapField(Class aClass, Map<String, Object> map) throws Exception {
Object bean = aClass.newInstance();
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
String key = entry.getKey();
Object value = entry.getValue();
//创建PropertyDescriptor 对象,获取去key相同的set/get方法
PropertyDescriptor descriptor = new PropertyDescriptor(key, bean.getClass());
//获取set方法
Method method = descriptor.getWriteMethod();
//获取形参列表内容
Object value1 = getBeanValue(value, method.getParameterTypes()[0]);
//执行提交
method.invoke(bean, value1);
}
return bean;
}