自定义BeanUtils

BeanUtils:

package com.icil.swift.milestone.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * *************************************************************************
 * <PRE>
 *  @ClassName:    : BeanUtils 
 *
 *  @Description:    : 
 *
 *  @Creation Date   : Jul 7, 2020 5:43:51 PM
 *
 *  @Author          :  Sea
 *  
 *
 * </PRE>
 **************************************************************************
 */
public abstract class BeanUtils extends org.springframework.beans.BeanUtils {

    public static void copyProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                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);
                        // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null && StringUtils.isNotBlank(value+"")) {
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }

    /**
     * distinct by key for list,
     * @param keyExtractor distinct condition
     * @param <T> bean
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }


    /**
     * compare the bean fields value if different
     * @param source obj
     * @param target obj
     * @return true/false
     * @throws Exception
     */
    public static boolean diffBean(Object source, Object target) throws Exception {
        boolean flag =true;
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> compareObj = target.getClass();
        Field[] fields = compareObj.getDeclaredFields();

        for (Field field : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), compareObj);
            Method getMethod = pd.getReadMethod();
            Object o1 = getMethod.invoke(source);
            Object o2 = getMethod.invoke(target);
            String s1 = o1 == null ? "" : o1.toString();
            String s2 = o2 == null ? "" : o2.toString();
            if (!s1.equals(s2)) flag = false;
        }


        return flag;
    }
}

方式2:

package com.icil.booking.service.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.icil.fw.logging.ICILLogger;
import com.icil.fw.logging.ICILLoggerFactory;

import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;

public class CglibBeanCopierUtils {

    private static final ICILLogger logger = ICILLoggerFactory
            .getInstance(CglibBeanCopierUtils.class);

    public static Map<String, BeanCopier> beanCopierMap = new HashMap<String, BeanCopier>();

    /**
     * @Title: copyProperties
     * @Description: TODO(bean属性转换)
     * @param source
     *            资源类
     * @param target
     *            目标类
     * @author yushaojian
     * @date 2015年11月25日下午4:56:44
     */
    public static void copyProperties(Object source, Object target) {
        String beanKey = generateKey(source.getClass(), target.getClass());
        BeanCopier copier = null;
        if (!beanCopierMap.containsKey(beanKey)) {
            copier = BeanCopier.create(source.getClass(), target.getClass(),
                    true);
            beanCopierMap.put(beanKey, copier);
        } else {
            copier = beanCopierMap.get(beanKey);
        }
        copier.copy(source, target, new Converter() {
            private final Map<String, BeanCopier> bcMap = new HashMap<String, BeanCopier>();

            @Override
            public Object convert(Object sourcePropVal, Class targetPropClazz,
                    Object targetSetMethodName) {
                /*logger.debug("======>>>>> sourcePropVal " + sourcePropVal
                        + "======>>>>>targetPropClazz " + targetPropClazz
                        + "======>>>>>targetSetMethodName "
                        + targetSetMethodName);*/
                /*if (BigDecimal.class.equals(targetPropClazz)) {
                    BigDecimal bd = null;
                    if (sourcePropVal != null && !"".equals(sourcePropVal)) {
                        bd = new BigDecimal(sourcePropVal.toString());
                        bd=bd.setScale(4, BigDecimal.ROUND_HALF_UP);  
                    }
                    return bd;
                } else if (Integer.class.equals(targetPropClazz)) {
                    Integer value = null;
                    if (sourcePropVal != null && !"".equals(sourcePropVal)) {
                        value = Integer.parseInt(sourcePropVal.toString());
                    }
                    return value;
                } else if (Date.class.equals(targetPropClazz)) {
                    Date date = null;
                    if(sourcePropVal!=null && !"".equals(sourcePropVal)){
                        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                        try {
                            date = sdf.parse((String)sourcePropVal);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    return date;
                }else if (int.class.equals(targetPropClazz)){
                    int value =0 ;
                    if (sourcePropVal != null && !"".equals(sourcePropVal)) {
                        value = Integer.parseInt(sourcePropVal.toString());
                    }
                    return value;
                }*/
                return sourcePropVal;
            }
        });
    }

    protected static Object convertListGenericType(Object sourcePropVal) {
        // TODO Auto-generated method stub
        return null;
    }

    private static String generateKey(Class<?> class1, Class<?> class2) {
        return class1.toString() + class2.toString();
    }
}
原文地址:https://www.cnblogs.com/lshan/p/9761994.html