PropertyDescriptor类
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1、getPropertyType(),获得属性的Class对象。
2、getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法。
3、hashCode(),获取对象的哈希值。
4、setReadMethod(Method readMethod),设置用于读取属性值的方法;setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法;
导包java.bean.*;
通过属性名获取对应的值,利用反射方法,如下:
ReflectPoint pt1 = new ReflectPoint(7,9);
String propertyName = "x";//给一个属性,获取值
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();//Read对应get()方法
Object reValue = methodGetX.invoke(pt1);
给某个属性设置值,如下:
String propertyName2 = "y";//给一个属性,设置值
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName2,pt1.getClass());
Method methodSetY = pd2.getWriteMethod();//Write对应set()方法
methodSetY.invoke(pt1,3);
通过这个原理可以实现map2Bean的操作。
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
1、getPropertyType(),获得属性的Class对象。
2、getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法。
3、hashCode(),获取对象的哈希值。
4、setReadMethod(Method readMethod),设置用于读取属性值的方法;setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法;
导包java.bean.*;
通过属性名获取对应的值,利用反射方法,如下:
ReflectPoint pt1 = new ReflectPoint(7,9);
String propertyName = "x";//给一个属性,获取值
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();//Read对应get()方法
Object reValue = methodGetX.invoke(pt1);
给某个属性设置值,如下:
String propertyName2 = "y";//给一个属性,设置值
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName2,pt1.getClass());
Method methodSetY = pd2.getWriteMethod();//Write对应set()方法
methodSetY.invoke(pt1,3);
通过这个原理可以实现map2Bean的操作。