深拷贝和浅拷贝是针对复杂数据类型(对象及数组)来说的,浅拷贝只拷贝一层,而深拷贝是层层拷贝。
深拷贝:深拷贝复制变量值,对于非基本类型的变量,则递归至基本类型变量后,再复制。 深拷贝后的对象与原来的对象是完全隔离的,互不影响,对一个对象的修改并不会影响另一个对象。
浅拷贝:浅拷贝是会将对象的每个属性进行依次复制,但是当对象的属性值是引用类型时,实质复制的是其引用,当引用指向的值改变时也会跟着变化。
public class BeanCovertUtils extends BeanUtils {
public static <S, T> T covertTo(S source, Supplier<T> targetSupplier) {
return covertTo(source, targetSupplier, null);
}
public static <S, T> List<T> covertListTo(List<S> sourceList, Supplier<T> targetSupplier) {
return covertListTo(sourceList, targetSupplier, null);
}
public static <S, T> T deepCovertTo(S source, Class<T> targetClass) {
if (source == null) {
return null;
}
String json = JSON.toJSONString(source);
return JSON.parseObject(json, targetClass);
}
public static <S, T> List<T> deepCovertListTo(List<S> sources, Class<T> targetClass) {
if (sources == null) {
return null;
}
String json = JSON.toJSONString(sources);
return JSON.parseArray(json, targetClass);
}
public static <S, T> T covertTo(S source, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
if (null == source || targetSupplier == null) {
return null;
}
T target = targetSupplier.get();
copyProperties(source, target);
if (callBack != null) {
callBack.callBack(source, target);
}
return target;
}
public static <S, T> List<T> covertListTo(List<S> sources, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
if (null == sources || null == targetSupplier) {
return null;
}
List<T> targets = new ArrayList<>(sources.size());
for(S source : sources) {
T target = targetSupplier.get();
copyProperties(source, target);
if (callBack != null) {
callBack.callBack(source, target);
}
targets.add(target);
}
return targets;
}
/**
* 回调接口
*
* @param <S> 源对象类型
* @param <T> 目标对象类型
*/
@FunctionalInterface
public interface ConvertCallBack<S, T> {
void callBack(S t, T s);
}
}