java对象或数组深拷贝

7 篇文章 0 订阅
/**
 * <h1>拷贝值</h1>
 * @param object
 * @return T
 * @date 2020/7/20 19:55
 * @author dengyw
 */
public final static <T> T copyObject(T object) throws AidpException {
    if (isNull(object)) {
        return null;
    } else if (object.getClass().isArray()) {
        Object[] objects = (Object[]) object;
        int length = objects.length;
        Object[] objectNews = (Object[]) Array.newInstance(object.getClass().getComponentType(), length);
        for (int i = 0; i < length; i++) {
            objectNews[i] = copyObject(objects[i]);
        }
        return (T) objectNews;
    } else if (object instanceof Map) {
        Map<Object, Object> cacheValueOldMap = (Map<Object, Object>) object;
        Map<Object, Object> cacheValueMap = (Map) ClassUtils.getInstanceByClass(object.getClass());
        for (Map.Entry entry : cacheValueOldMap.entrySet()) {
            cacheValueMap.put(copyObject(entry.getKey()), copyObject(entry.getValue()));
        }
        return (T) cacheValueMap;
    } else if (object instanceof Collection) {
        Collection<Object> collectionOlds = (Collection<Object>) object;
        Collection<Object> collectionNews = null;
        try {
            collectionNews = (Collection<Object>) ClassUtils.getInstanceByClass(object.getClass());
        } catch (Exception e) { //防止出现Arrays.ArrayList时出现异常
            LOGGER.error("copy Collection:[{}] exception", object.getClass().getName(), e);
            collectionNews = new ArrayList<Object>();
        }
        for (Object objectEntry : collectionOlds) {
            collectionNews.add(copyObject(objectEntry));
        }
        return (T) collectionNews;
    } else if (isBaseType(object)) {
        return object;
    } else if (object instanceof Date) {
        if (object instanceof Timestamp) {
            return (T) new Timestamp(((Timestamp) object).getTime());
        } else if (object instanceof java.sql.Date) {
            return (T) new java.sql.Date(((java.sql.Date) object).getTime());
        }
        return (T) new Date(((Date) object).getTime());
    } else {
        return copyImplSerializable(object);
    }
}

/**
 * <h1>使用流拷贝对象</h1>
 * @param object
 * @return T
 * @date 2020/7/20 18:40
 * @author dengyw
 */
public final static <T> T copyImplSerializable(T object) throws AidpException {
    if(LOGGER.isWarnEnabled()){
        LOGGER.warn("using stream copy, copy class:[" + object.getClass() + "], optimization is recommended");
    }
    try {
        return (T) byteArrayToObject(objectToByteArray(object), object.getClass());
    } catch (Exception e) {
        throw new AidpException(BaseErrorEnum.COPY_OBJECT_ERROR, new Object[]{object}, e);
    }
}

/**
 * <h1>对象转为字节数组</h1>
 * @param object
 * @return byte[]
 * @date 2020/8/14 23:08
 * @author dengyw
 */
public final static byte[] objectToByteArray(Object object) throws AidpException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;

    //如果子类没有继承序列化接口,这一步会报错
    try {
        if(!(object instanceof Serializable)){
            throw new AidpException(BaseErrorEnum.OBJECT_UNREALIZED_SERIALIZABLE_ERROR, new Object[]{object});
        }
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        return baos.toByteArray();
    } catch (Exception e) {
        throw new AidpException(BaseErrorEnum.OBJECT_TO_BYTE_ARRAY_ERROR, new Object[]{object}, e);
    } finally {
        if(baos != null){
            try {
                baos.close();
            } catch (Exception e) {
                LOGGER.error("close ByteArrayOutputStream is exception", e);
            }
        }
        if(oos != null){
            try {
                oos.close();
            } catch (Exception e) {
                LOGGER.error("close ObjectOutputStream is exception", e);
            }
        }
    }
}

/**
 * <h1>字节数组转为对象</h1>
 * @param bytes
 * @return T
 * @date 2020/8/14 23:08
 * @author dengyw
 */
public final static <T> T byteArrayToObject(byte[] bytes, Class<T> clazz) throws AidpException {
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;

    Object copyObject = null;
    //如果子类没有继承序列化接口,这一步会报错
    try {
        bais = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bais);
        copyObject = ois.readObject();
        if(clazz.isInstance(copyObject)){
            return (T) copyObject;
        } else {
            throw new AidpException(BaseErrorEnum.OBJECT_DESERIALIZATION_ERROR, new Object[]{clazz, copyObject.getClass()});
        }
    } catch (Exception e) {
        throw new AidpException(BaseErrorEnum.BYTE_ARRAY_TO_OBJECT_ERROR, e);
    } finally {
        if(bais != null){
            try {
                bais.close();
            } catch (Exception e) {
                LOGGER.error("close ByteArrayInputStream is exception", e);
            }
        }
        if(ois != null){
            try {
                ois.close();
            } catch (Exception e) {
                LOGGER.error("close ObjectInputStream is exception", e);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值