前言: BeanUtils默认的populate方法不会忽略空值和null值,在特定场景,我们需要原始的值避免被覆盖,所以这里提供一种自定义实现方式。
package com.hmwl.service.program;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ContextClassLoaderLocal;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author: martin
* @Date: 2023/11/01 15:13 pm
* @Description: apache common 原版populate不会过滤null值,不符合使用场景
*/
@Slf4j
public class CustomBeanUtils extends BeanUtilsBean {
private static final ContextClassLoaderLocal
BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() {
// Creates the default instance used when the context cl服务器托管网assloader is unavailable
@Override
protected CustomBeanUtils initialValue() {
return new CustomBeanUtils();
}
};
public static CustomBeanUtils getInstance() {
return BEANS_BY_CLASSLOADER.get();
}
public static void setInstance(final CustomBeanUtils newInstance) {
BEANS_BY_CLASSLOADER.set(newInstance);
}
public static void populateIgnoreEmpty(final Object bean, final Map properties) {
try {
CustomBeanUtils.getInstance().populateIgnoreNull(bean, properties);
} catch (IllegalAccessException e) {
log.error(e.getMessage());
} catch (InvocationTargetException e) {
log.error(e.getMessage());
}
}
private final void populateIgnoreNull(final Object bean, final Map properties)
throws IllegalAccessException, InvocationTargetException {
if ((bean == null) || (properties == null)) {
return;
}
if (log.isDebugEnabled()) {
log.debug("BeanUtils.populate(" + bean + ", " +
properties + ")");
}
for (final Map.Entry entry : properties.entrySet()) {
final String name = entry.getKey();
// 增强下,因为可能多次调用,当value为null的时候不赋值
if (name == null || entry.getValue() == null) {
continue;
}
setProperty(bean, name, entry.getValue());
}
}
}
原版实现:
public void populate(final Object bean, final Map properties)
throws IllegalAccessException, InvocationTargetException {
// Do nothing unless both arguments have been specified
if ((bean == null) || (properties == null)) {
return;
}
if (log.isDebugEnabled()) {
log.debug("BeanUtils.populate(" + bean + ", " +
服务器托管网 properties + ")");
}
// Loop through the property name/value pairs to be set
for(final Map.Entry entry : properties.entrySet()) {
// Identify the property name and value(s) to be assigned
final String name = entry.getKey();
if (name == null) {
continue;
}
// Perform the assignment for this property
setProperty(bean, name, entry.getValue());
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
相关推荐: Adobe Acrobat Pro DC 2023详细安装教程
Adobe Acrobat Pro DC 2023是Adobe 公司推出的一款专业的PDF 文档编辑和管理工具,它拥有丰富的功能,包括编辑、组织、存储和共享PDF 文件,以及对PDF 文件的安全保护。 安装包请搜索公众号 可唯的学堂。 本篇提供Windows …