【问题标题】:Should we use clone or BeanUtils.copyProperties and why我们应该使用 clone 还是 BeanUtils.copyProperties 以及为什么
【发布时间】:2024-01-06 03:24:01
【问题描述】:

从外观上看 - BeanUtils.copyProperties 似乎创建了一个对象的克隆。如果是这种情况,那么关于实现 Cloneable 接口的问题是什么(只有不可变对象是新的,而可变对象复制了引用)这是最好的,为什么?

我昨天实现了可克隆,然后意识到我必须为非 String/Primative 元素提供自己的修改。然后我被告知我现在正在使用的BeanUtils.copyProperties。两种实现似乎都提供了类似的功能。

谢谢

【问题讨论】:

  • 那么你到底想问什么?
  • 我们应该使用 clone 还是 BeanUtils.copyProperties 以及为什么

标签: java spring clone


【解决方案1】:

我检查了源代码,发现它只是复制了 primitive 属性的“第一级”。当涉及到嵌套对象时,嵌套属性仍然引用原始对象的字段,因此它不是“深拷贝”。

org.springframework.beans.BeanUtils.java 的 Spring 源代码中检查这个 sn-ps,版本 5.1.3:

/**
     * 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);
    }

...

    /**
     * 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, @Nullable Class<?> editable,
            @Nullable 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);
                        }
                    }
                }
            }
        }
    }

只关注以下几行:

Object value = readMethod.invoke(source);
...
writeMethod.invoke(target, value);

这一行调用目标对象的setter。想象一下这个类:

class Student {
    private String name;
    private Address address;
}

如果我们有student1student2,第二个只是intanciated 并且没有分配任何字段,student1address1 和名称John

所以,如果我们调用:

    BeanUtils.copyProperties(student1, student2);

我们正在做:

    student2.setName(student1.getName()); // this is copy because String is immutable
    student2.setAddress(student1.getAddress()); // this is NOT copy, we still are referencing `address1`

address1 改变时,student2 也会改变。

所以,BeanUtils.copyProperties() 仅适用于对象的原始类型字段;如果是嵌套的,则不起作用;或者,您必须确保原始对象在目标对象的整个生命周期内的不变性,这并不容易且可取。


如果你真的想把它变成一个深拷贝,你必须实现一些方法来递归地在非原始字段上调用这个方法。最后你会到达一个只有原始/不可变字段的类,然后你就完成了。

【讨论】:

    【解决方案2】:

    对于任何类的 Objects 的深拷贝,最好的解决方案是递归处理 Object 内部的 Object,并且使用真正的 GET 和 SET 函数来维护 Object Integrity。

    我想提出的解决方案是找到Source Object的所有GET函数,并将它们与Target Object的SET函数匹配。如果它们在 ReturnType -> Parameter 中匹配,则执行复制。如果它们不匹配,请尝试为这些内部对象调用深层复制。

    private void objectCopier(Object SourceObject, Object TargetObject) {
            // Get Class Objects of Source and Target
            Class<?> SourceClass = SourceObject.getClass();
            Class<?> TargetClass = TargetObject.getClass();
            // Get all Methods of Source Class
            Method[] sourceClassMethods = SourceClass.getDeclaredMethods();
            for(Method getter : sourceClassMethods) {
                String getterName = getter.getName();
                // Check if method is Getter
                if(getterName.substring(0,3).equals("get")){
                    try {
                        // Call Setter of TargetClass with getter return as parameter
                        TargetClass.getMethod("set"+getterName.substring(3), getter.getReturnType()).invoke(TargetObject, getter.invoke(SourceObject));
                    }catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                        try {
                            // Get Class of the type Setter in Target object is expecting
                            Class<?> SetTargetClass = TargetClass.getMethod(getterName).getReturnType();
                            // Create new object of Setter Parameter of Target
                            Object setTargetObject = SetTargetClass.newInstance();
                            // Copy properties of return object of the Source Object to Target Object
                            objectCopier(getter.invoke(SourceObject), setTargetObject);
                            // Set the copied object to the Target Object property
                            TargetClass.getMethod("set"+getterName.substring(3),SetTargetClass).invoke(TargetObject, setTargetObject);
                        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                                | NoSuchMethodException | SecurityException | InstantiationException ef) {
                            System.out.println(getterName);
                        }
                    }
                }
            }
        }
    

    【讨论】:

      【解决方案3】:

      Josh Bloch 提供了一些相当好的论据(包括您提供的论据)断言 Cloneable 存在根本缺陷,而是支持复制构造函数。见here

      我还没有遇到过复制不可变对象的实际用例。您出于特定原因复制对象,大概是为了将一组可变对象隔离到单个事务中进行处理,确保在该处理单元完成之前没有任何内容可以更改它们。如果它们已经是不可变的,那么引用就像副本一样好。

      BeanUtils.copyProperties 通常是一种侵入性较小的复制方式,无需更改要支持的类,它在合成对象方面提供了一些独特的灵活性。

      也就是说,copyProperties 并不总是一刀切。您可能在某些时候需要支持包含具有专用构造函数但仍然是可变的类型的对象。您的对象可以支持内部方法或构造函数来解决这些异常,或者您可以将特定类型注册到某些外部工具中进行复制,但它无法到达甚至 clone() 可以到达的某些地方。这很好,但仍有限制。

      【讨论】:

      • Josh Bloch's Effective Java 注释的好答案。我可以总结一下“两者都可以根据情况使用”吗?但两者都有限制。
      • 我认为copyProperties()只是调用目标的setter,并不“深”,因为当涉及到嵌套对象时,内部字段仍然是引用,而不是副本。检查我的答案以查看源代码。
      • @WesternGun 你想得对。任何认为copyProperties 在一次调用中进行“深度”复制的人都是错误的。
      【解决方案4】:

      我认为您正在寻找深层副本。您可以在 util 类中使用以下方法并将其用于任何类型的对象。

      public static <T extends Serializable> T copy(T input) {
          ByteArrayOutputStream baos = null;
          ObjectOutputStream oos = null;
          ByteArrayInputStream bis = null;
          ObjectInputStream ois = null;
          try {
              baos = new ByteArrayOutputStream();
              oos = new ObjectOutputStream(baos);
              oos.writeObject(input);
              oos.flush();
      
              byte[] bytes = baos.toByteArray();
              bis = new ByteArrayInputStream(bytes);
              ois = new ObjectInputStream(bis);
              Object result = ois.readObject();
              return (T) result;
          } catch (IOException e) {
              throw new IllegalArgumentException("Object can't be copied", e);
          } catch (ClassNotFoundException e) {
              throw new IllegalArgumentException("Unable to reconstruct serialized object due to invalid class definition", e);
          } finally {
              closeQuietly(oos);
              closeQuietly(baos);
              closeQuietly(bis);
              closeQuietly(ois);
          }
      }
      

      【讨论】:

        【解决方案5】:

        克隆由您完成。如果您尝试克隆的实例包含另一个实例的引用,您也必须向该实例编写克隆代码。 如果实例包含对其他实例的引用链怎么办? 因此,如果您自己进行克隆,您可能会遗漏一个小细节。

        另一方面,BeanUtils.copyProperties 自己处理所有事情。 它可以减少您的工作量。

        【讨论】:

          【解决方案6】:

          BeanUtils 比标准克隆更灵活,标准克隆只是将字段值从一个对象复制到另一个对象。 clone 方法从同一类的 bean 中复制字段,但 BeanUtils 可以为具有相同属性名称的不同类的 2 个实例执行此操作。

          例如,假设您有一个具有字符串日期字段的 Bean A 和具有相同字段 java.util.Date 日期的 bean B。使用 BeanUtils,您可以复制字符串值并使用 DateFormat 自动将其转换为日期。

          我用它来将 SOAP 对象转换为不具有相同数据类型的 Hibernate 对象。

          【讨论】:

          • 现在在 spring 4.x 之后它确实比较了 soruce 和 destination beans 的原始类型。所以在使用 BeanUtils 复制属性时要小心。请记住,您确实有相同的原始类型,可以从源分配到目标
          【解决方案7】:

          根据您的问题,我猜您需要对象的深拷贝。如果是这种情况,请不要使用clone 方法,因为它已在oracle docs 中指定,它提供了关联对象的浅拷贝。而且我对BeanUtils.copyProperties API 没有足够的了解。
          下面是deep copy 的简短演示。在这里,我正在深度复制primitive array。您可以使用任何类型的对象尝试此代码。

          import java.io.*;
          class ArrayDeepCopy 
          {
              ByteArrayOutputStream baos;
              ByteArrayInputStream bins;
              public void saveState(Object obj)throws Exception //saving the stream of bytes of object to `ObjectOutputStream`.
              {
                  baos = new ByteArrayOutputStream();
                  ObjectOutputStream oos = new ObjectOutputStream(baos);
                  oos.writeObject(obj);
                  oos.close();
              }
              public int[][] readState()throws Exception //reading the state back to object using `ObjectInputStream`
              {
                  bins = new ByteArrayInputStream(baos.toByteArray());
                  ObjectInputStream oins = new ObjectInputStream(bins);
                  Object obj = oins.readObject();
                  oins.close();
                  return (int[][])obj;
              }
              public static void main(String[] args) throws Exception
              {
                  int arr[][]= {
                                  {1,2,3},
                                  {4,5,7}
                              };
                  ArrayDeepCopy ars = new ArrayDeepCopy();
                  System.out.println("Saving state...");
                  ars.saveState(arr);
                  System.out.println("State saved..");
                  System.out.println("Retrieving state..");
                  int j[][] = ars.readState();
                  System.out.println("State retrieved..And the retrieved array is:");
                  for (int i =0 ; i < j.length ; i++ )
                  {
                      for (int k = 0 ; k < j[i].length ; k++)
                      {
                          System.out.print(j[i][k]+"\t");
                      }
                      System.out.print("\n");
                  }
          
              }
          }
          

          【讨论】:

            【解决方案8】:

            克隆创建对象的浅拷贝,克隆对象始终与原始对象属于同一类。复制所有字段,无论是否私有。

            BeanUtils.copyProperties API 在属性名称相同的所有情况下,将属性值从源 bean 复制到目标 bean。

            在我看来,这两个概念没有什么共同点。

            【讨论】:

            • 嗨。我不是在质疑你的判断,只是扮演魔鬼代言人。克隆的目的不就是用相同的数据创建一个相同类型的对象吗?如果您使用创建一个空对象(空白画布)并复制属性 - 我们本质上不是在做同样的事情吗?