Introspector类:
将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。
主要方法(都是静态方法):
public static BeanInfo getBeanInfo(Class> beanClass) 在 JavaBean 上进行内省,了解其所有属性、公开的方法和事件。 - 将要分析的 bean 类
BeanInfo类:
封装了JavaBean属性的信息。
主要方法:
PropertyDescriptor[] getPropertyDescriptors() 获得所有属性的描述,可以采用遍历BeanInfo的方法,来查找、设置类的属性。
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:1. getPropertyType(),获得属性的Class对象;2.getReadMethod(),获得用于读取属性值的方法;//等同于getxxx()方法getWriteMethod(),获得用于写入属性值的方法;//等同于setxxx()方法3. hashCode(),获取对象的哈希值;4. setReadMethod(Method readMethod),设置用于读取属性值的方法;5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。 6.getName();//返回属性的名字
示例代码:
@Test
public void test1() throws Exception
{
Class> c = Class.forName("com.qq.java.introspector.Student");
Constructor> con = c.getConstructor();
Student stu = (Student) con.newInstance();
//获取封装的属性信息
BeanInfo bf = Introspector.getBeanInfo(c);
//获取PropertyDescriptor
PropertyDescriptor[] pds = bf.getPropertyDescriptors();
//遍历属性
String property = null;
for (PropertyDescriptor pd : pds)
{
if (!(property = pd.getName()).equals("class")) //注意会有Class对象
{
//m等同于setName(String name),setAge(int age)
Method m = pd.getWriteMethod();
if(property.equals("name"))
{
m.invoke(stu, "Jack");
}
if(property.equals("age"))
{
m.invoke(stu, 10);
}
//m2等同于getName(),getAge();
Method m2 = pd.getReadMethod();
//因为getName(),getAge()没有参数,所以invoke方法只有调用者
System.out.println(m2.invoke(stu));
}
}
}
可以看出,内省操作比较繁琐的,所以Apache开发了一套简单、易用的API来操作Bean的属性——BeanUtils工具包。
BeanUtils工具包:
下载:http://commons.apache.org/beanutils/
注意:应用的时候还需要一个logging包 http://commons.apache.org/logging/关于BeanUtils工具包的使用留到下一篇再细细研究一下。beanClass