BeanUtils.copyProperties 封装对时间类型的转化 Date处理

BeanUtils.copyProperties 封装对时间类型的转化 Date处理

package com.powerpeak.adstation.common;

import com.powerpeak.adstation.modules.asset.domain.AssetStake;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
* Created by IntelliJ IDEA.
* @author: LiuZe
* @Created: 2019/8/2 14:32
*/
public class MyBeanUtils extends BeanUtils {
	
	public static final Logger LOGGER =LoggerFactory.getLogger(MyBeanUtils.class);

    static {
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        ConvertUtils.register(new DateConvert(), java.sql.Date.class);
    }

    /**
     * 复制 map的值到对象中
     * @param updateProperties
     * @param bean
     * @param 
     */
    public static <T> void copyPropertiesInclude(Map<String, Object> updateProperties, T bean){
        Set<Map.Entry<String, Object>> revisabilityFiledSet = updateProperties.entrySet();
        for (Map.Entry<String, Object> entry : revisabilityFiledSet) {
            Object value = entry.getValue();
            if(value != null){
                try {
                    org.apache.commons.beanutils.BeanUtils.setProperty(bean, entry.getKey(), value);
                } catch (Exception e) {
                    LOGGER.info("MyBeanUtils copyPropertiesInclude Exception : "+e.getMessage());
                }
            }
        }
    }

}


class DateConvert implements Converter {

    public static final Logger LOGGER = LoggerFactory.getLogger(DateConvert.class);

    @Override
    public Object convert(Class arg0, Object arg1) {
        String p = (String)arg1;
        if(p== null || p.trim().length()==0){
            return null;
        }
        try{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.parse(p.trim());
        }
        catch(Exception e){
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                return df.parse(p.trim());
            } catch (ParseException ex) {
                LOGGER.info("MyBeanUtils DateConvert Exception : "+e.getMessage());
                return null;
            }
        }
    }
}

你可能感兴趣的:(java)