BeanUtils copyProperties API to ignore null and specific propertie

自古美人都是妖i 提交于 2019-12-04 01:24:28
edu

If you want to ignore null-value you have to do it with the following line of code before copying properties:

BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);

In case you are using the org.springframework.beans.BeanUtils you can ignore specific properies using the method copyProperties(Object source, Object target, String... ignoreProperties). An example,

BeanUtils.copyProperties(sourceObj, targetObj, "aProperty", "another");

This is a sample code snippet which I am using for skip the null fields while copying to target. You can add checks for specific properties using property name, value etc. I have used org.springframework.beans.BeanUtils

public static void copyNonNullProperties(Object src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}

public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for (PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null)
            emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!