JAVA对象拷贝类

JAVA程序经常需要对对象进行拷贝,提供一份对象拷贝类,不同类型对象之间以属性名进行映射,属性相同的进行拷贝。

代码如下,仅供参考。

package com.iflytek.adsring.service.common.util;

import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;


public class BeanUtil {
    /**
     * 支持对象间值拷贝(不同类型则以属性名相同时映射)
     * @param orig
     * @param clazzT
     * @return
     */
    public static  T copy(Object orig,Class clazzT) {
        try {
            Object dest=clazzT.newInstance();

            if (orig == null) {
                return null;
            }

            PropertyDescriptor[] destDescriptors = PropertyUtils.getPropertyDescriptors(clazzT);

            for (int i = 0; i < destDescriptors.length; i++) {
                String destName = destDescriptors[i].getName();
                Class destType = destDescriptors[i].getPropertyType();
                if("class".equals(destName)){
                    continue;
                }
                Object value = null;
                if (PropertyUtils.isReadable(orig, destName) && PropertyUtils.isWriteable(dest, destName)) {
                    try {
                        value = PropertyUtils.getSimpleProperty(orig, destName);
                    }catch (NoSuchMethodException ex){
                        //不存在的属性,则跳过
                        continue;
                    }
                    //如果是列表
                    if(destType.isArray()){
                        //TODO
                    }else if(destType.isPrimitive() || destType.isEnum() || destType.getName().startsWith("java.")){
                        //nothing to do
                    }
                    else {
                        //当前对象不是简单对象时,递归copy
                        value = copy(PropertyUtils.getSimpleProperty(orig, destName), destType);
                    }
                    PropertyUtils.setSimpleProperty(dest, destName, value);
                }
            }
            return (T)dest;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * List值拷贝
     * @param origList
     * @param clazzT
     * @return
     */
    public static  List copy(List origList,Class clazzT) {
        try {
            List destList = new ArrayList();
            if (origList == null || origList.size() <= 0) {
                return null;
            }

            for (int i = 0; i < origList.size(); i++) {
                destList.add(copy(origList.get(i),clazzT));
            }
            return destList;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

你可能感兴趣的:(JAVA对象拷贝类)