深拷贝和浅拷贝
项目里面碰到的一个真实的问题
对应spring 中的原型模型,对象中的属性比较多的时候,我们采用的是复制的方式,怎么高效的复制出来一个对象,这其中又涉及到深拷贝和浅拷贝
最开始我们使用的一种方式是使用Spring bean 中的org.springframework.beans.BeanUtils#instantiate方法通过class 去创建一个新的实例,源码如下:
/** * Convenience method to instantiate a class using its no-arg constructor. * @param clazz class to instantiate * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated * @see Class#newInstance() */ public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException { Assert.notNull(clazz, "Class must not be null"); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { return clazz.newInstance(); } catch (InstantiationException ex) { throw new BeanInstantiationException(clazz, "Is it an abstract class?", ex); } catch (IllegalAccessException ex) { throw new BeanInstantiationException(clazz, "Is the constructor accessible?", ex); } }
房里就是通过 clazz.newInstance() 返回一个新的对象,获取到这个对象后,再使用 copyProperties方法将属性拷贝过去,源码如下:
/** * Copy the property values of the given source bean into the target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * <p>This is just a convenience method. For more complex transfer needs, * consider using a full BeanWrapper. * @param source the source bean * @param target the target bean * @throws BeansException if the copying failed * @see BeanWrapper */ public static void copyProperties(Object source, Object target) throws BeansException { copyProperties(source, target, null, (String[]) null); }
而实际上内部调用的copyProperties,再来看看:
/** * Copy the property values of the given source bean into the given target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
实际上是对属性for循环遍历完成最终的设置
那么我们写了一个util方法去通过这种方式实现bean 拷贝,使用Spring 自带的工具类实现:
public class BeanCopyUtil { /** * 不同类型对象数据copy * * @param source * @param targetClass * @param <T> * @return */ public static <T> T copyProperties(Object source, Class<T> targetClass) { T target = BeanUtils.instantiate(targetClass); BeanUtils.copyProperties(source, target); return target; } }
但是这种方式只是实现了浅拷贝,如果一个对象中包含的另外的一个dto,在拷贝的时候实际上获得的是指向同一个对象的引用,后面会有结果展示
那么怎么实现深拷贝呢,其实很多种方式:
1.用fastjson的序列化方法
WaybillDTO waybillDTOJsonFrom = JsonUtil.fromJson(JsonUtil.toJson(waybillDTO),WaybillDTO.class);
将对象waybillDTO序列化成json串后 再反序列化出来,这样得到的是一个实现了深拷贝的对象,具体的可以去看 fromJson方法内部的实现,这种方法的缺点是我们知道序列化和反序列化的耗时是比较高的
2.通过字节流转换
通过将对象转换成字节流,分配内存,生成新的对象:
public static <T extends Serializable> T deepClone(T obj) { T cloneObj = null; try { //写入字节流 ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(out); obs.writeObject(obj); obs.close(); //分配内存,写入原始对象,生成新对象 ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray()); ObjectInputStream ois = new ObjectInputStream(ios); //返回生成的新对象 cloneObj = (T) ois.readObject(); ois.close(); } catch (Exception e) { throw new IllegalArgumentException("bean深度拷贝异常", e); } return cloneObj; }
这三种方式的生成的对象对比的结果我们看下,定义对象 WaybillDTO,里面包含了一个Map对象 :Map<String, String> extendMessage ,那么对这个WaybillDTO进行拷贝后的结果验证一下:
//long start1 = System.currentTimeMillis(); WaybillDTO waybillDTOClone = BeanCopyUtil.deepClone(waybillDTO); // System.out.println(System.currentTimeMillis() - start1); System.out.println("waybillDTO==waybillDTOClone:" + (waybillDTO==waybillDTOClone)); System.out.println("waybillDTO.getExtendMessage==waybillDTOClone.getExtendMessage:" + (waybillDTO.getExtendMessage()==waybillDTOClone.getExtendMessage())); //long start2 = System.currentTimeMillis(); WaybillDTO targetWaybillInfo = BeanCopyUtil.copyProperties(waybillDTO, WaybillDTO.class); // System.out.println(System.currentTimeMillis() - start2); System.out.println("waybillDTO==targetWaybillInfo:" + (waybillDTO==targetWaybillInfo)); System.out.println("waybillDTO.getExtendMessage==targetWaybillInfo.getExtendMessage:" + (waybillDTO.getExtendMessage()==targetWaybillInfo.getExtendMessage())); // long start3 = System.currentTimeMillis(); WaybillDTO waybillDTOJsonFrom = JsonUtil.fromJson(JsonUtil.toJson(waybillDTO),WaybillDTO.class); // System.out.println(System.currentTimeMillis() - start3); System.out.println("waybillDTO==waybillDTOJsonFrom:" + (waybillDTO==waybillDTOJsonFrom)); System.out.println("waybillDTO.getExtendMessage==waybillDTOClone.getExtendMessage:" + (waybillDTO.getExtendMessage()==waybillDTOJsonFrom.getExtendMessage()));
看下对应是效果,可以看到通过方法2 Spring 的beanUtils 实现的对象拷贝,对内部的Map<String, String> extendMessage对比的结果是true,方法1和方法3都是false,说明是不同的对象
waybillDTO==waybillDTOClone:false waybillDTO.getExtendMessage==waybillDTOClone.getExtendMessage:false
waybillDTO==targetWaybillInfo:false waybillDTO.getExtendMessage==targetWaybillInfo.getExtendMessage:true
waybillDTO==waybillDTOJsonFrom:false waybillDTO.getExtendMessage==waybillDTOClone.getExtendMessage:false Process finished with exit code 0
浙公网安备 33010602011771号