對象拷貝工具類


import org.apache.commons.beanutils.PropertyUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 對象拷貝工具類
 */
public class BeanUtil {

	/**
	 * 獲取Obj對象的fieldName屬性的值
	 */
	private static Object getFieldValue(Object obj, String fieldName) {
		Object fieldValue = null;
		if(null == obj) {
			return null;
		}
		Method[] methods = obj.getClass().getDeclaredMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if(methodName.startsWith("get") && methodName.substring(3).toUpperCase().equals(fieldName.toUpperCase())) {
				try {
					fieldValue = method.invoke(obj, new Object[] {});
				} catch (Exception e) {
					System.out.println("取值出錯,方法名 " + methodName);
					continue;
				}
			}
		}
		return fieldValue;
	}

	public static Map<String, Object> objectToMap(Object obj) throws Exception{
		if(obj == null){
			return null;
		}
		Map<String, Object> map = new HashMap<>();
		Field[] declaredFields = obj.getClass().getDeclaredFields();
		for (Field field : declaredFields) {
			field.setAccessible(true);
			map.put(field.getName(), field.get(obj));
		}
		return map;
	}

	/**
	 * 拷貝對象屬性到目標對象
	 * <p>
	 * <b>示例</b> BeanSource bs = new BeanSource(); bs.set(...); ... BeanTarget
	 * bt = BeanUtil.copyProperties(bs,BeanTarget.class);
	 *
	 * </p>
	 *
	 * @param sourceObj
	 *            源對象
	 * @param targetClazz
	 *            目標類
	 * @return 目標對象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T copyProperties(Object sourceObj, Class<?> targetClazz) {
		T targetObj = null;
		try {
			if(sourceObj==null){
				return targetObj;
			}
			targetObj = (T) targetClazz.newInstance();
			PropertyUtils.copyProperties(targetObj, sourceObj);
		}  catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		return targetObj;
	}

	/**
	 * 拷貝對象屬性到目標對象,應用於已存在了目標對象,使用源對象豐富目標對象的屬性值
	 */
	public static boolean copyProperties(Object sourceObj, Object targetObj) {
		boolean flag = false;
		try {
			PropertyUtils.copyProperties(targetObj, sourceObj);
			flag = true;
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e.getMessage());
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e.getMessage());
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e.getMessage());
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		return flag;
	}

	/**
	 * 拷貝源列表對象到目標列表
	 * @param sourceList 源列表
	 * @param targetClazz 目標列表元類型
	 * @return 目標列表
	 */
	public static <T> List<T> copyBeans(List<?> sourceList, Class<?> targetClazz)
			throws InstantiationException, IllegalAccessException {

		if (sourceList == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}
		List<T> targetList = new ArrayList<T>();
		for (Object sourceObj : sourceList) {
			T targetObj = copyProperties(sourceObj, targetClazz);
			targetList.add(targetObj);
		}
		return targetList;
	}

	/**
	 * 將一個 JavaBean 對象轉化爲一個 Map
	 * @param bean 要轉化的JavaBean 對象
	 * @return 轉化出來的 Map 對象
	 * @throws IntrospectionException 如果分析類屬性失敗
	 * @throws IllegalAccessException 如果實例化 JavaBean 失敗
	 * @throws InvocationTargetException 如果調用屬性的 setter 方法失敗
	 */
	public static Map<String, Object> convertBean(Object bean) throws IntrospectionException, IllegalAccessException,InvocationTargetException {
        Class<? extends Object> type = bean.getClass();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }

    /**
     * 判斷對象是否爲空或屬性全爲空
     */
    public static boolean isBeanPropertiesNull(Object bean)throws IntrospectionException, IllegalAccessException,InvocationTargetException {
        if (bean == null) {
            return true;
        }
        Class<? extends Object> type = bean.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    return false;
                }
            }
        }
        return true;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章