Java中把一个对象属性不为空的复制给另外一个对象

第一种写法

BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
beanUtilsBean.getConvertUtils().register(false, true, 0);
beanUtilsBean.copyProperties(destObject, srcObject);

第二种写法

ObjectUtils.clone(srcObject, new CloneNullsStrategy());

以上两种基于apache.commons

参考地址1

第三种写法基于spring的写法:

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

public class BeanUtils extends org.springframework.beans.BeanUtils
{
    public static void copyNotNullProperties(Object source, Object target, String[] ignoreProperties)
            throws BeansException
    {
        copyNotNullProperties(source, target, null, ignoreProperties);
    }

    public static void copyNotNullProperties(Object source, Object target, Class<?> editable)
            throws BeansException
    {
        copyNotNullProperties(source, target, editable, null);
    }

    public static void copyNotNullProperties(Object source, Object target)
            throws BeansException
    {
        copyNotNullProperties(source, target, null, null);
    }

    private static void copyNotNullProperties(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 ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;

        for (PropertyDescriptor targetPd : targetPds)
            if ((targetPd.getWriteMethod() != null) && ((ignoreProperties == null) || (!ignoreList.contains(targetPd.getName())))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if ((sourcePd != null) && (sourcePd.getReadMethod() != null))
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source, new Object[0]);
                        if ((value != null) || (readMethod.getReturnType().getName().equals("java.lang.String"))) {
                            boolean isEmpty = false;
                            if ((value instanceof Set)) {
                                Set s = (Set)value;
                                if ((s == null) || (s.isEmpty()))
                                    isEmpty = true;
                            }
                            else if ((value instanceof Map)) {
                                Map m = (Map)value;
                                if ((m == null) || (m.isEmpty()))
                                    isEmpty = true;
                            }
                            else if ((value instanceof List)) {
                                List l = (List)value;
                                if ((l == null) || (l.size() < 1))
                                    isEmpty = true;
                            }
                            else if ((value instanceof Collection)) {
                                Collection c = (Collection)value;
                                if ((c == null) || (c.size() < 1)) {
                                    isEmpty = true;
                                }
                            }
                            if (!isEmpty) {
                                Method writeMethod = targetPd.getWriteMethod();
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, new Object[] { value });
                            }
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
            }
    }

    public static Object getNestedProperty(Object bean, String nestedProperty)
    {
        try
        {
            return PropertyUtils.getNestedProperty(bean, nestedProperty);
        }
        catch (Exception e) {
            e.printStackTrace();
        }return null;
    }

    public static void setPropertyValue(Object bean, String property, Object value)
    {
        try
        {
            PropertyUtils.setNestedProperty(bean, property, value);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void copyPropertyValue(Object source, Object target)
    {
        try
        {
            Method[] sourceMethods = source.getClass().getMethods();
            Method[] targetMethods = target.getClass().getMethods();
            Method sourceMethod = null;
            String sourceMethodName = "";
            String targetMehodName = "";
            String str = "";
            String targetfield = "";
            for (int i = 0; i < sourceMethods.length; i++) {
                sourceMethod = sourceMethods[i];
                sourceMethodName = sourceMethod.getName();
                if ((sourceMethodName.startsWith("get")) && (!sourceMethodName.equals("getClass")))
                    for (int j = 0; j < targetMethods.length; j++) {
                        targetMehodName = targetMethods[j].getName();
                        if ((targetMehodName.startsWith("get")) &&
                                (sourceMethodName.equals(targetMehodName))) {
                            str = targetMehodName.substring(3, targetMehodName.length());
                            targetfield = str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
                            setPropertyValue(target, targetfield, sourceMethod.invoke(source, new Object[0]));
                        }
                    }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void setPropertyValue(Object bean, String property, Object value, boolean ignoreCase)
    {
        if (ignoreCase)
            try {
                PropertyDescriptor[] pds = getPropertyDescriptors(bean.getClass());
                for (PropertyDescriptor pd : pds)
                    if (pd.getName().equalsIgnoreCase(property))
                        PropertyUtils.setNestedProperty(bean, pd.getName(), value);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        else
            setPropertyValue(bean, property, value);
    }
}

第四种写法

import org.apache.commons.beanutils.BeanUtilsBean;
import java.lang.reflect.InvocationTargetException;

public class MyBeansUtil extends BeanUtilsBean {

@Override
public void copyProperty(Object dest, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    if(value == null) return;
    super.copyProperty(dest, name, value);
    }
}

参考地址2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值