Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeanUtils copyProperties API to ignore null and specific propertie

Spring's BeanUtils.copyProperties() provides option to ignore specific properties while copying beans:

public static void copyProperties(Object source,
                 Object target,
                 String[] ignoreProperties) throws BeansException

Does the Apache Commons BeanUtils provide a similar feature?

Also is it possible to ignore null values while using Spring's BeanUtils.copyProperties(), I see this feature with Commons BeanUtils:

Date defaultValue = null;
DateConverter converter = new DateConverter(defaultValue);
ConvertUtils.register(converter, Date.class);

Can I achieve the same with Spring's BeanUtils?

like image 923
Arun Avatar asked Jul 02 '13 04:07

Arun


2 Answers

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);
}
like image 96
Prajith Vb Avatar answered Oct 07 '22 11:10

Prajith Vb


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");
like image 32
Georgios Syngouroglou Avatar answered Oct 07 '22 11:10

Georgios Syngouroglou