Jakarta Commons——BeanUtils

    技术2026-10-01  1

    参考guide内容

          http://commons.apache.org/beanutils/v1.8.1/apidocs/org/apache/commons/beanutils/package-summary.html

    PropertyUtils

    作用:属性的get和set操作

    属性分为四种:simple(String),index(List),map(Map),Object,都可以用以下方法获得:

            String city = (String) PropertyUtils.getProperty(employee,                "subordinate[3].address(home).city");

            类似 employee.getSubordinate[3].getAddress(home).getCity();

    获得属性类型  getPropertyType

    BeanUtils

            一个比较常用的功能是Bean Copy,也就是copy bean的属性。如果做分层架构开发的话就会用到,比如从PO(Persistent Object)拷贝数据到VO(Value Object),copyProperties()方法还可以将一个Map的内容复制进bean中,前提是Map各键一一对应于目的

    DynaBean

            当bean的属性是动态生成的,如包装其他集合(resultSet,map)为bean。该bean需要实现DynaBean接口。

    步骤:先使用DynaClass创建一个包含DynaProperty的类;再产生对象赋值给DynaBean;使用PropertyUtils实现动态的get和set

    如包装ResultSet:

            RowSetDynaClass rsdc = new RowSetDynaClass(rs);         List rows = rsdc.getRows();

    WrapDynaBean and WrapDynaClass:包装已存在的javabean,转换其为DynaBean.

    1. LazyDynaBean - A Lazy DynaBean2. LazyDynaMap - A light weight DynaBean facade to a Map with lazy map/list processing 3. LazyDynaList - A lazy list for DynaBean's, java.util.Map's or POJO beans. 4. LazyDynaClass - A MutableDynaClass implementation.

    Collections

    BeanComparator

          基于Bean的公有属性的Comparator

    BeanPropertyValueChangeClosure

           用于设置Bean的属性值,常和CollectionUtils组合使用设置Collection中所有Bean的某一属性。如设置所有Collection中的activeEmployee属性为true

          // create the closure

        BeanPropertyValueChangeClosure closure =         new BeanPropertyValueChangeClosure( "activeEmployee", Boolean.TRUE );     // update the Collection     CollectionUtils.forAllDo( peopleCollection, closure );

    BeanPropertyValueEqualsPredicate

                   判断属性值是否为某一值.可以用于Collections的过滤,如得到Collections所有activeEmployee属性为true的bean:

        BeanPropertyValueEqualsPredicate predicate =         new BeanPropertyValueEqualsPredicate( "activeEmployee", Boolean.FALSE );     // filter the Collection     CollectionUtils.filter( peopleCollection, predicate );

    BeanToPropertyTransformer

           得到Bean 属性的取值 ,如 找到collections中所有bean的city属性的值  组成的list:

        // create the transformer     BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "person.address.city" );     // transform the Collection,peoplesCities只包含city的集合     Collection peoplesCities = CollectionUtils.collect( peopleCollection, transformer );

       

    最新回复(0)