使用BeanUtils.describe将对象转换成Map时,数组字段的值只获取到第一个元素

情景:在开发过程中,需要将两个对象实体的值进行对比

处理:使用BeanUtils.describe将两个对象转换成Map进行遍历对比数据,注意:

BeanUtils是org.apache.commons.beanutils下的

问题:发现BeanUtils.describe转换后的Map的泛型是<String,String>此时获取到的字段如果是数组类型的话只获取了第一个元素

解决:使用PropertyUtils.describe方法的到的Map的泛型是<String,Object>此时可以正常获取到数据

BeanUtils.describe和PropertyUtils.describe都是将对象转换成Map,如果对象的字段存在数组或者集合类型的,使用PropertyUtils.describe。

Map<String, String> map = BeanUtils.describe(Object bean);

Map<String, Object> map = PropertyUtils.describe(Object bean);

代码如下:

@Data
public class Person implements Serializable {//实体
 
    /**
     * 
     */
    private static final long serialVersionUID = 3193754045080382621L;
 
    private String            name;
    private Integer           sex;
    private Integer           age;
    private String            school;
    private String[]          hobby;
    private List<String>      place;
 
}
  public static void main(String[] args) {//测试
        Person p = new Person();
        p.setName("Akili");
        p.setSex(1);
        p.setAge(24);
        p.setSchool(null);
        p.setHobby(new String[] { "摄影", "旅行", "家居", "做饭" });
        p.setPlace(Lists.newArrayList("北京","深圳","广州","北海"));
 
        Map<String, String> beanLog = new HashMap<String, String>();
        Map<String, Object> propertyLog = new HashMap<String, Object>();
        try {
            beanLog = BeanUtils.describe(p);
        } catch (Exception e) {
            LOG.info("error message", e);
            return;
        }
        try {
            propertyLog = PropertyUtils.describe(p);
        } catch (Exception e) {
            LOG.info("error message", e);
            return;
        }
        if (beanLog != null && propertyLog != null) {
            for (Map.Entry<String, String> entry : beanLog.entrySet()) {
                Map<String, String> temp = new HashMap<String, String>();
                if (entry.getKey().equals("hobby")) {
                    System.out.println("beanLog hobby --- :" + entry.getValue());
                    System.out.println("propertyLog hobby --- :" + Arrays.toString((String[])propertyLog.get(entry.getKey())));
                }
                if(entry.getKey().equals("place")){
                    System.out.println("beanLog place --- :" + entry.getValue());
                    System.out.println("propertyLog place --- :" + propertyLog.get(entry.getKey()));
                }
            }
        }
 
    }

结果:
beanLog place --- :北京
propertyLog place --- :[北京, 深圳, 广州, 北海]
beanLog hobby --- :摄影
propertyLog hobby --- :[摄影, 旅行, 家居, 做饭]

猜你喜欢

转载自blog.csdn.net/zhangleiyes123/article/details/112311814
今日推荐