Java 内省机制

来源:互联网 发布:泰迪狗狗衣服秋冬淘宝 编辑:程序博客网 时间:2024/05/20 00:53

内省机制

内省(Introspector)是Java对Bean类属性、事件的一种缺省处理方法。SUN公司开发了一套API,专门用于操作java对象的属性。
通过内省技术访问(java.beans包提供了内省的API)JavaBean的两种方式:
- 通过PropertyDescriptor类操作Bean的属性。
- 通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。

代码:

/** * JavaBean */public class Person {    private String name;    private int age;    private Date birthday;    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;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public int getId() {        return 1;    }}
@Testpublic void test1() throws IntrospectionException{    //Introspector构建BeanInfo对象,BeanInfo将Person的所有属性进行了封装    BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);    //属性描述器,能取到Person和父类中的属性    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();    System.out.println("Person属性个数: " + pds.length);    for (PropertyDescriptor propertyDescriptor : pds) {        System.out.println("Person属性: " + propertyDescriptor.getName());    }}@Testpublic void test2() throws Exception{    Person person = new Person();    //属性描述器,能获取setter和getter方法    PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);    //设置属性    Method setter = pd.getWriteMethod();    setter.invoke(person, "james");    //获取属性    Method getter = pd.getReadMethod();    System.out.println(getter.invoke(person, null));}

Beanutils工具包

Apache组织开发了一套用于操作JavaBean的API,这套API考虑到了很多实际开发中的应用场景,因此在实际开发中很多程序员使用这套API操作JavaBean,以简化程序代码的编写。
常用类:
- BeanUtils
- PropertyUtils
- ConvertUtils.regsiter(Converter convert, Class clazz)
- 自定义转换器

代码:

@Testpublic void test3() throws Exception{    //BeanUtils默认支持8种基本数据类型,自动转换    //赋值    BeanUtils.setProperty(Person.class, "name", "curry");    //取值    String name = BeanUtils.getProperty(Person.class, "name");    System.out.println(name);}@Testpublic void test4() throws Exception{    Person person = new Person();    //注册类型转换器    ConvertUtils.register(new DateLocaleConverter(), Date.class);    BeanUtils.setProperty(person, "birthday", "2017-7-23");    String birthday = BeanUtils.getProperty(person, "birthday");    System.out.println(birthday);}@Testpublic void test5() throws Exception{    Map<String,Object> map = new HashMap<String,Object>();    map.put("name", "张三");    map.put("age", 23);    map.put("birthday", "2008-8-8");    //注册时间类型转换器    ConvertUtils.register(new DateLocaleConverter(), Date.class);    Person person = new Person();    //将map属性封装到person中    BeanUtils.populate(person, map);    System.out.println(person);}
原创粉丝点击