属性的复制BeanUtils

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;

/**
 */
public class CopyBeanUtil  {

    /**
     * 复制bean
     * @param source
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> T  copyBean(Object source,Class<T> classType){
        T obj = null;
        if(source == null){
            return null;
        }

        try {
            obj = classType.newInstance();
            BeanUtils.copyProperties(source,obj);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }


    /**
     * 复制list
     * @param source
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> List<T>  copyList(List source,Class<T> classType){
        List<T> returnlist = new ArrayList<>();

        if(source == null){
            return null;
        }

        try {
            Integer size= source.size();
            for(int i=0;i<size;i++){
                T obj = classType.newInstance();
                BeanUtils.copyProperties(source.get(i),obj);
                returnlist.add(obj);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return returnlist;
    }

    /**
     * copy bean 过滤掉空字段
     * @param src
     * @param target
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }


    private 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);
    }

    /**
     * 将一个 Map 对象转化为一个 JavaBean
     * @param type 要转化的类型
     * @param map 包含属性值的 map
     * @param <T> 转化出来的 JavaBean
     * @return
     * @throws Exception
     */
    public static <T>T copyMap(Class<T> type, Map map) throws Exception {

        T obj = type.newInstance(); // 创建 JavaBean 对象
        // 给 JavaBean 对象的属性赋值
        ExtBeanUtils.populate(obj, map);

        return obj;
    }

    /**
     * 将一个 List<Map> 对象转化为一个 List<JavaBean>
     * @param type 要转化的类型
     * @param mapList 包含属性值的 mapList
     * @param <T> 转化出来的 List<JavaBean>
     * @return
     * @throws Exception
     */
    public static <T>List<T> copyMapList(Class<T> type, List<Map<String,Object>> mapList) throws Exception{


        if(mapList == null){
            return null;
        }

        List<T> objectList = new ArrayList<>();
        T obj = null;

        for (Map map : mapList) {
            obj = type.newInstance(); // 创建 JavaBean 对象
            ExtBeanUtils.populate(obj, map);
            objectList.add(obj);
        }
        return objectList;
    }


}
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class ExtBeanUtils extends BeanUtils {
    static {
		ConvertUtils.register(new DateConvert(), java.util.Date.class);
		ConvertUtils.register(new DateConvert(), java.sql.Date.class);
		ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class);
	}

    public static void populate(Object bean, Map<String, ? extends Object> properties) throws IllegalAccessException, InvocationTargetException {
        BeanUtils.populate(bean, properties);
    }
}
import org.apache.commons.beanutils.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateConvert implements Converter {
   private static String dateFormatStr = "yyyy/MM/dd";
	private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateFormatStr);
	private static String dateLongFormatStr = dateFormatStr+" HH:mm:ss";
	private static SimpleDateFormat dateTimeLongFormat = new SimpleDateFormat(dateLongFormatStr);
   @Override
	public Object convert(Class arg0, Object arg1) {
		if(arg1 == null) return null;
		String className = arg1.getClass().getName();
		//java.sql.Timestamp
		if ("java.sql.Timestamp".equalsIgnoreCase(className)) {
			try {
				SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");
				return df.parse(dateTimeLongFormat.format(arg1));
			} catch (Exception e) {
				try {
					SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);
					return df.parse(dateTimeFormat.format(arg1));
				} catch (ParseException ex) {
					e.printStackTrace();
					return null;
				}
			}
		}else{
		    //java.util.Date,java.sql.Date
			String p = (String) arg1;
			if (p == null || p.trim().length() == 0) {
				return null;
			}
			try {
				SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");
				return df.parse(p.trim());
			} catch (Exception e) {
				try {
					SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);
					return df.parse(p.trim());
				} catch (ParseException ex) {
					e.printStackTrace();
					return null;
				}
			}
		}
	}
	public static String formatDateTime(Object obj) {
		if (obj != null)
			return dateTimeFormat.format(obj);
		else
			return "";
	}
	public static String formatLongDateTime(Object obj) {
		if (obj != null)
			return dateTimeLongFormat.format(obj);
		else
			return "";
	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值