Bis*_*128 25 java spring clone
从它的外观 - BeanUtils.copyProperties似乎创建一个对象的克隆.如果是这种情况,那么关于实现Cloneable接口的问题(只有不可变对象是新的,因为可变对象有复制的引用)这是最好的,为什么?
我昨天实现了cloneable,然后意识到我必须为非String/Primative元素提供我自己的修改.然后我被告知BeanUtils.copyProperties我现在正在使用哪个.两种实现似乎都提供了类似的功能.
谢谢
pha*_*ers 26
Josh Bloch提供了一些相当不错的论据(包括你提供的论点)断言这Cloneable是有根本性的缺陷,而是偏向于复制构造函数.看到这里.
我还没有遇到复制不可变对象的实际用例.您出于特定原因复制对象,可能是为了将一组可变对象隔离到一个事务中进行处理,保证在处理单元完成之前不会改变它们.如果它们已经是不可变的,那么引用就像副本一样好.
BeanUtils.copyProperties 通常是一种不那么具有侵入性的复制方式,无需改变要支持的类,它在合成对象时提供了一些独特的灵活性.
也就是说,copyProperties并不总是一刀切.您可能在某些时候需要支持包含具有专门构造函数的类型的对象,但仍然是可变的.您的对象可以支持内部方法或构造函数来解决这些异常,或者您可以将特定类型注册到某些外部工具进行复制,但它无法到达某些地方甚至clone()可以.这很好,但仍然有限制.
BeanUtils 比简单地将字段值从一个对象复制到另一个对象的标准克隆更灵活。clone 方法从同一类的 bean 中复制字段,但 BeanUtils 可以为具有相同属性名称的不同类的 2 个实例执行此操作。
例如,假设您有一个 Bean A 有一个字段 String date 和一个 bean B 有相同的字段 java.util.Date date。使用 BeanUtils,您可以复制字符串值并使用 DateFormat 将其自动转换为日期。
我用它来将 SOAP 对象转换为不具有相同数据类型的 Hibernate 对象。
我检查了源代码,发现它只是复制原始属性的“第一级” 。当涉及嵌套对象时,嵌套属性仍然引用原始对象的字段,因此它不是“深拷贝”。
从org.springframework.beans.BeanUtils.java5.1.3 版的Spring 源代码中检查此片段:
/**
* 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);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
只关注这一行:
writeMethod.invoke(target, value);
Run Code Online (Sandbox Code Playgroud)
此行调用目标对象上的 setter。想象一下这个类:
class Student {
private String name;
private Address address;
}
Run Code Online (Sandbox Code Playgroud)
如果我们有student1and student2,第二个只是被初始化并且没有分配任何字段,student1hasaddress1和 name John。
所以,如果我们调用:
BeanUtils.copyProperties(student1, student2);
Run Code Online (Sandbox Code Playgroud)
我们正在做:
student2.setName(student1.getName()); // this is copy because String is immutable
student2.setAddress(student1.getAddress()); // this is NOT copy, we still are referencing `address1`
Run Code Online (Sandbox Code Playgroud)
当address1改变时,它也会改变student2。
因此,BeanUtils.copyProperties() 仅适用于对象的原始类型字段;如果是嵌套的,则不起作用;或者,你必须在目标对象的整个生命周期中确保原始对象的不变性,这并不容易和可取。
如果你真的想让它成为一个深拷贝,你必须实现某种方式来递归调用这个方法在不是基元的字段上。最后,您将到达一个只有原始/不可变字段的类,然后您就完成了。
| 归档时间: |
|
| 查看次数: |
36474 次 |
| 最近记录: |