Bean変換object

2234 ワード

T ,? 
package com.starry.test;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import com.alibaba.fastjson.JSON;
import com.mysql.fabric.xmlrpc.base.Array;


/**
 * bean 
 * @author Starry
 *
 */
public class BeanConvertor {

/**
*  : bean bean 
* 
* @param object
* @param entityClass
* @return
*/
public static  T convertBean(Object object, Class entityClass) {
if(null == object) {
return null;
}
return JSON.parseObject(JSON.toJSONString(object), entityClass);
}


/**
*  : 
* 
* @param source	 
* @param target	 
* @param ignoreProperties	 copy 
* @return
*/
public static  T copy(Object source, Class target, String...ignoreProperties){
T targetInstance = null;
try {
targetInstance = target.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
if(ArrayUtils.isEmpty(ignoreProperties)) {
BeanUtils.copyProperties(source, targetInstance);
}else {
BeanUtils.copyProperties(source, targetInstance, ignoreProperties);
}
return targetInstance;

}

/**
*  : (List)
* 
* @param list	 
* @param target	 
* @param ignoreProperties	 copy 
* @return
*/
public static  List copyList(List list, Class target, String...ignoreProperties){
List targetList = new ArrayList<>();
if(CollectionUtils.isEmpty(list)) {
return targetList;
}
for(E e : list) {
targetList.add(copy(e, target, ignoreProperties));
}
return targetList;
}

/**
*  :map 
* 
* @param map
* @param t
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static  T mapToObject(Map map, Class t) throws
 InstantiationException, IllegalAccessException, InvocationTargetException 
{
T instance = t.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(instance, map);
return instance;
}

/**
*  : Map
* 
* @param object
* @return
*/
public static Map, ?> objectToMap(Object object){
return convertBean(object, Map.class);
}
}