javav7 list转换对象类型工具类




import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
 
 
 
public class ObjectCopyUtils {
 
    private static final Logger logger = LoggerFactory.getLogger(ObjectCopyUtils.class);
 
    /**
     * obj转obj
     *
     * @param origin
     * @param clazz
     * @param 
     * @return
     */
    public static  T convert(Object origin, Class clazz) {
        Object dest = null;
        if (null != origin) {
            try {
                dest = clazz.newInstance();
                copyProperties(dest, origin);
            } catch (InstantiationException e) {
                dest = null;
                logger.error("InstantiationException getBean error. ", e);
            } catch (IllegalAccessException e) {
                dest = null;
                logger.error("IllegalAccessException getBean error. ", e);
            }
        }
 
        return (null != dest) ? (T) dest : null;
    }
 
    /**
     * list转list
     *
     * @param srcList
     * @param targetClazz
     * @param 
     * @param 
     * @return
     */
    public static  List convert(Collection srcList, Class targetClazz) {
        if (CollectionUtils.isEmpty(srcList)) {
            return Collections.emptyList();
        }
        T target = null;
        try {
            List dist = new ArrayList();
            for (S src : srcList) {
                //目标类注意必须实现空构造函数
                target = targetClazz.newInstance();
                copyProperties(target, src);
                dist.add(target);
            }
            return dist;
        } catch (Exception e) {
            logger.error("对象{}复制属性出错:{}", targetClazz.getSimpleName(), JSONUtils.toString(srcList));
            throw new IllegalArgumentException("对象" + targetClazz.getSimpleName() + "复制属性出错", e);
        }
    }
 
    private static void copyProperties(Object dest, Object origin) {
        if (null == origin) {
            dest = null;
            return;
        }
        try {
            BeanUtils.copyProperties(origin, dest);
        } catch (BeansException e) {
            logger.error("BeansException copyProperties error.", e);
        }
    }
}

你可能感兴趣的:(javav7 list转换对象类型工具类)