f-angi
5/31/2016 - 1:13 PM

Returns a list of an object's non-empty properties

Returns a list of an object's non-empty properties

import org.apache.commons.beanutils.PropertyUtils;

public List<String> getNotEmptyObjectProperties(Object object) {

    List<String> notEmptyProperties = new ArrayList<String>();

    if (object == null) {
        return notEmptyProperties;
    }

    try {
        for (Entry<String, Object> entry : PropertyUtils.describe(object).entrySet()) {
            Object obj = entry.getValue();
            if (obj == null || obj instanceof Class) {
                continue;
            }
            if (obj instanceof String) {
                if (!((String) obj).trim().isEmpty()) {
                    notEmptyProperties.add(entry.getKey());
                }
            }
            else if (obj instanceof Collection) {
                if (!((Collection<?>) obj).isEmpty()) {
                    notEmptyProperties.add(entry.getKey());
                }
            }
            else {
                notEmptyProperties.addAll(getNotEmptyObjectProperties(obj));
            }
        }
    }
    catch (Exception e) {
        LOGGER.error("", e);
        return notEmptyProperties;
    }

    return notEmptyProperties;
}