BeanConvert.java 2.61 KB
package com.yoho.unions.convert;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xieyong
 *
 */
@Component
public class BeanConvert implements Convert{
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	//拷贝不支持对象里面嵌套对象拷贝
	/* (non-Javadoc)
	 * @see com.yoho.product.convert.Convert#convertFrom(java.lang.Object, java.lang.Object, java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public final  <T> T convertFrom(Object source, Object target, Class<T> clazz) {
		if (source == null){
			return null;
		}
		Preconditions.checkNotNull(target, "target can't be null");
		BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false);

		copier.copy(source, target, null);
		return (T) target;
	}

	/**
	 * 将多个对象拷贝到一个目的对象, 不需要实例化目的对象
	 *
	 * @param targetClazz 目的对象的CLASS
	 * @param sources 源对象
	 * @param <T> 目的对象类型
	 *
	 * @return 目的对象实例, 拷贝之后的结果
	 * @author create by DengXinFei 2016-1-23
	 */
	public static <T>T copyBeans(Class<T> targetClazz, Object... sources){
		if(null == sources || sources.length == 0){
			return null;
		}
		T targetObj = null;
		try{
			targetObj = targetClazz.newInstance();
			for(Object sourceObj: sources){
				BeanCopier copier = BeanCopier.create(sourceObj.getClass(), targetClazz, false);
				copier.copy(sourceObj, targetObj, null);
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return targetObj;
	}


	/* (non-Javadoc)
	 * @see com.yoho.product.convert.Convert#convertFromList(java.util.List, java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public final <T> List<T> convertFromList(List<? extends Object> sourceList,Class<T> clazz) {
		if(CollectionUtils.isEmpty(sourceList))
		{
			return new ArrayList<T>(0);
		}
		BeanCopier copier = BeanCopier.create(sourceList.get(0).getClass(), clazz, false);
		List<T> list=Lists.newArrayList();
		//这里反射性能可能不佳,要测试 
		try
		{	
			Object target=null;
			for (Object t : sourceList) {
				target=clazz.newInstance();
				copier.copy(t, target, null);
				list.add((T)target);
			}
		}
		catch (Exception e) {
			log.error("other exception" ,e);
			throw new RuntimeException("other exception",e);
		}
		return list;
	}

}