【问题标题】:Is there a recursive version of BeanUtils.populate?是否有 BeanUtils.populate 的递归版本?
【发布时间】:2014-09-13 11:34:29
【问题描述】:

org.apache.commons.beanutils.BeanUtils:

BeanUtils.populate(Object bean, Map<String,? extends Object> properties);
Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.

是否有 BeanUtils.populate 的递归版本?

class Person {
  String name;
  Address address;
}
class Address {
  String street;
  int number
}

所以在 Person 上调用填充,它也会填充地址(假设 Address 有一个默认构造函数)。

【问题讨论】:

    标签: java apache-commons


    【解决方案1】:

    您可以使用 dot(.) 来做到这一点。假设您想在地址对象中设置街道,请指定属性名称,例如address.street 例如

    Map<String, String> propertyMap = new HashMap<String, String>();
    propertyMap.put("name", "James Bond");
    propertyMap.put("address.street", "London");
    propertyMap.put("address.number", "007");
    
    BeanUtilsBean.getInstance().populate(bean, propertyMap);
    

    【讨论】:

    • 这仅在 bean.address != null 时有效。即 BeanUtilsBean.populate() 没有实例化 Address。
    • List
      怎么样?
    • @arisalexis 对于集合字段,propertyMap.put("addressList[0].number", "007");
    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 2011-06-23
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多