beanToMap
    public static <T> Map<String, Object>  beanToMap(T t)  {
        Map<String, Object> result = new HashMap<>();
        try {
            Field[] fields = t.getClass().getDeclaredFields();
            //遍历字段
            int offset = 0;
            for (int i = 0; i < fields.length; i++) {
                //获取字段
                Field field = fields[i];
                //设置私有属性可访问
                field.setAccessible(true);
                //获取字段上注解
                Transient annotation = field.getAnnotation(Transient.class);
                if (annotation != null) {
                    //存在该注解
                    offset++;
                    continue;
                }
                //获取值
                Object value = field.get(t);
                if(value!=null&&!value.equals("")){
                    result.put(field.getName(),value);
                }

            }
        }catch (IllegalAccessException e){
                e.printStackTrace();
        }
        return  result;
    }

 

   public static <T> String genInsertSql(String table,T data){
        Map<String, Object> bean = beanToMap(data);
        String key = StringUtils.join(bean.keySet(), ",");
        List<Object> collect = bean.values().stream().map(v -> {
            if (v instanceof String) {
                return "'" + v + "'";
            }
            if (v instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dataStr = sdf.format((Date) v);
                return  dataStr ;
            }
            return v;
        }).collect(Collectors.toList());
        String sql= "insert into "+table+"( "+ key+" ) values( "+StringUtils.join(collect, ",")+" )"  ;
        return  sql;
    }

 

 

BeanUtils:

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import com.alibaba.fastjson.JSONObject;
/**
 * *************************************************************************
 * <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)
                        {
                            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 false;};
        }
        return flag;
    }

    
    /**
     * compare the bean fields value if different
     * @param source obj
     * @param target obj
     * @return true/false
     * @throws Exception
     */
    public static JSONObject getDiff(Object source, Object target) throws Exception {
        JSONObject diff =new JSONObject();
        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)) 
            {
                diff.put(field.getName(), Arrays.asList(s1,s2));
            };
        }
        return diff;
    }
    
    
    /**
     * compare the bean fields value if different
     * @param source obj
     * @param target obj
     * @return true/false
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static JSONObject getMapDiff(Map<String,Object> source, Map<String,Object> target) throws Exception {
          Assert.notNull(source, "Source must not be null");
          Assert.notNull(target, "Target must not be null");
          JSONObject diff =new JSONObject();
          source.forEach((k,v)->
          {
              String v1=v+"";
              String v2 = target.get(k)+"";
              if (!v1.equals(v2)) 
              {
                  diff.put(k, Arrays.asList(v1,v2));
              };
          });
        return diff;
    }
    
    

    /**
     * 判断对象中属性值是否全为空
     * @param object
     * @return
     */
    public static boolean allFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

}

 

比较两个对象,并且比较出对象list 下的不同

    /**
     * compare the bean fields value if different
     * @param source obj
     * @param target obj
     * @return true/false
     * @throws Exception
     */
    public static JSONObject getDiff(Object source, Object target) throws Exception {
        JSONObject diff =new JSONObject();
        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))
            {
                //处理list
                if(o1 instanceof Collection){
                    Collection<Object> o11 = (Collection) o1;
                    Collection<Object> o22 = (Collection) o2;
                    Collection common = o11.stream().filter(o -> o22.contains(o)).collect(Collectors.toList());
                    o11.removeAll(common);
                    o22.removeAll(common);
                    diff.put(field.getName(), Arrays.asList(o11,o22));
                }else {
                    diff.put(field.getName(), Arrays.asList(s1,s2));
                }

            };
        }
        return diff;
    }

 

 

 

 

方式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();
    }
}

 

posted on 2018-10-09 18:20  lshan  阅读(458)  评论(0编辑  收藏  举报