All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.domain.CloneableBase Maven / Gradle / Ivy

There is a newer version: 2.3.5.RELEASE
Show newest version
package com.feingto.cloud.domain;

import org.springframework.cglib.beans.BeanCopier;

import java.lang.reflect.Array;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 深度复制
 *
 * @author longfei
 * TODO: 使用lombok的@Accessors(chain = true)时,无法复制
 */
public class CloneableBase implements ICloneable {
    private static ConcurrentMap, BeanCopier> beanCopiers = new ConcurrentHashMap<>();

    private static Object clone(Object bean) {
        if (Objects.isNull(bean)) {
            return null;
        } else if (bean instanceof ICloneable) {
            return ((ICloneable) bean).clone();
        } else {
            if (bean.getClass().isArray() && !bean.getClass().getComponentType().equals(byte.class)) {
                int length = Array.getLength(bean);
                Object clone = Array.newInstance(bean.getClass().getComponentType(), length);
                for (int i = 0; i < length; i++) {
                    Array.set(clone, i, clone(Array.get(bean, i)));
                }
                return clone;
            } else {
                return bean;
            }
        }
    }

    private static BeanCopier createCopier(Class clz) {
        if (beanCopiers.containsKey(clz)) {
            return beanCopiers.get(clz);
        }
        beanCopiers.putIfAbsent(clz, BeanCopier.create(clz, clz, true));
        return beanCopiers.get(clz);

    }

    @Override
    public Object clone() {
        try {
            Object clone = this.getClass().newInstance();
            BeanCopier copier = createCopier(this.getClass());
            copier.copy(this, clone, (pojo, fieldType, fieldName) -> clone(pojo));
            return clone;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy