java 如何复制非空对象属性值

 更新时间:2021年09月01日 11:43:25   作者:zml_2015  
这篇文章主要介绍了java 如何复制非空对象属性值的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

java 复制非空对象属性值

很多时候,我们需要通过对象拷贝,比如说VO类与数据库实体bean类、更新时非空对象不更新,对同一对象不同数据分开存储等

用于对象拷贝,spring 和 Apache都提供了相应的工具类方法,BeanUtils.copyProperties

但是对于非空属性拷贝就需要自己处理了

在这里借用spring中org.springframework.beans.BeanUtils类提供的方法

copyProperties(Object source, Object target, String... ignoreProperties)

/**
     * Copy the property values of the given source bean into the given target bean,
     * ignoring the given "ignoreProperties".
     * <p>Note: The source and target classes do not have to match or even be derived
     * from each other, as long as the properties match. Any bean properties that the
     * source bean exposes but the target bean does not will silently be ignored.
     * <p>This is just a convenience method. For more complex transfer needs,
     * consider using a full BeanWrapper.
     * @param source the source bean
     * @param target the target bean
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
        copyProperties(source, target, null, ignoreProperties);
 
/**
     * Copy the property values of the given source bean into the given target bean.
     * <p>Note: The source and target classes do not have to match or even be derived
     * from each other, as long as the properties match. Any bean properties that the
     * source bean exposes but the target bean does not will silently be ignored.
     * @param source the source bean
     * @param target the target bean
     * @param editable the class (or interface) to restrict property setting to
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
            throws BeansException {
 
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
 
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                        "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
 
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null &&
                            ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source);
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                        catch (Throwable ex) {
                            throw new FatalBeanException(
                                    "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }
    }

然后封装一下得到以下方法

/**
     * @author zml2015
     * @Email zhengmingliang911@gmail.com
     * @Time 2017年2月14日 下午5:14:25
     * @Description <p>获取到对象中属性为null的属性名  </P>
     * @param source 要拷贝的对象
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
 
        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.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);
    }
 
    /**
     * @author zml2015
     * @Email zhengmingliang911@gmail.com
     * @Time 2017年2月14日 下午5:15:30
     * @Description <p> 拷贝非空对象属性值 </P>
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

测试方法就不提供了,自行测试即可

如果项目中使用的框架有Hibernate的话,则可以通过在实体类上添加下面两条注解

@DynamicInsert(true)
@DynamicUpdate(true)

如果想对该注解进一步了解的话,那么可以去官网看英文文档,文档解释的很清楚,在此不再赘述了

java对象属性复制的几种方式

1.使用java反射机制

获取对象的属性和get、set方法进行复制;

2.使用spring-beans5.0.8包中的BeanUtils类

import org.springframework.beans.BeanUtils;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
BeanUtils.copyProperties(sourceObject, targetObject);

3.使用cglib3.2.8包中的net.sf.cglib.beans.BeanCopier类

import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true);--第三个参数表示是否使用转换器,false表示不使用,true表示使用
Converter converter = new CopyConverter();--自定义转换器
beanCopier.copy(sourceObject, targetObject, converter);

转换器(当源对象属性类型与目标对象属性类型不一致时,使用转换器):

import net.sf.cglib.core.Converter;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.Date;
/**
 * Created by asus on 2019/7/12.
 */
public class CopyConverter implements Converter {
    @Override
    public Object convert(Object value, Class target, Object context) {
        {
            String s = value.toString();
            if (target.equals(int.class) || target.equals(Integer.class)) {
                return Integer.parseInt(s);
            }
            if (target.equals(long.class) || target.equals(Long.class)) {
                return Long.parseLong(s);
            }
            if (target.equals(float.class) || target.equals(Float.class)) {
                return Float.parseFloat(s);
            }
            if (target.equals(double.class) || target.equals(Double.class)) {
                return Double.parseDouble(s);
            }
            if(target.equals(Date.class)){
                while(s.indexOf("-")>0){
                    s = s.replace("-", "/");
                }
                return  new Date(s);
            }
            if(target.equals(BigDecimal.class)){
                if(!StringUtils.isEmpty(s)&&!s.equals("NaN")){
                    return  new BigDecimal(s);
                }
            }
            return value ;
        }
    }
}

4.使用spring-core5.0.8包

中的org.springframework.cglib.beans.BeanCopier类(用法与第三种一样)

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
Converter converter = new SpringCopyConverter();
BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true);
beanCopier.copy(sourceObject, targetObject, converter);

经过循环复制测试(源对象与目标对象各160个属性):

  • 第一种:Java反射通过判断属性类型,常用类型的属性值都能复制,但是不优化的前提下效率最慢;
  • 第二种:属性类型不同时无法复制,且效率相对较慢;
  • 第三种:耗时最少,不使用转换器时,属性类型不同时无法复制,使用转换器后,耗时会相对变长;
  • 第四种:与第三种相似,但是耗时相对较长;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringAMQP的使用方式案例详解

    SpringAMQP的使用方式案例详解

    这篇文章主要介绍了SpringAMQP的使用方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-01-01
  • 解决mybatisplus MetaObjectHandler 失效的问题

    解决mybatisplus MetaObjectHandler 失效的问题

    本文主要介绍了解决mybatisplus MetaObjectHandler 失效的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • Java打乱ArrayList生成一个随机序列列表

    Java打乱ArrayList生成一个随机序列列表

    有时候会需要将一个ArrayList或者数组中的数字打乱,方便后续使用,比如随机出题、答案选项打乱、连线题打乱、抽奖号码打乱等等,把我自己写的一段代码贴出来分享给大家。
    2016-08-08
  • 初探Java内部类的使用

    初探Java内部类的使用

    Java内部类一般可以分为以下三种:成员内部类、静态内部类和匿名内部类。这篇文章主要带大家初探一下Java内部类的使用,感兴趣的可以了解一下
    2022-09-09
  • GC算法实现垃圾优先算法

    GC算法实现垃圾优先算法

    为什么会存在那么多的垃圾回收算法呢?我想这个问题的答案可能是没有任何一种内存回收算法是完美的,所以在针对不同的情景需求下,不同的内存回收算法有其独特的优势,所以最后就延续了多种回收算法
    2022-01-01
  • idea 设置支持ES6语法的操作

    idea 设置支持ES6语法的操作

    这篇文章主要介绍了idea设置支持ES6语法的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • 客户端Socket与服务端ServerSocket串联实现网络通信

    客户端Socket与服务端ServerSocket串联实现网络通信

    这篇文章主要为大家介绍了客户端Socket与服务端ServerSocket串联实现网络通信的内容详解,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2022-03-03
  • 浅谈SpringBoot资源初始化加载的几种方式

    浅谈SpringBoot资源初始化加载的几种方式

    在平时的业务模块开发过程中,难免会需要做一些全局的任务、缓存、线程等等的初始化工作,那么如何解决这个问题呢?本文就来介绍一下,感兴趣的可以了解一下
    2021-07-07
  • 详解Java的文件与目录管理以及输入输出相关操作

    详解Java的文件与目录管理以及输入输出相关操作

    这篇文章主要介绍了详解Java的文件与目录管理以及输入输出相关操作,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09
  • OpenFeign在传递参数为对象类型是为空的问题

    OpenFeign在传递参数为对象类型是为空的问题

    这篇文章主要介绍了OpenFeign在传递参数为对象类型是为空的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03

最新评论