Java 我们应该使用clone还是BeanUtils.copyProperties?为什么
从外观上看-Java 我们应该使用clone还是BeanUtils.copyProperties?为什么,java,spring,clone,Java,Spring,Clone,从外观上看-BeanUtils.copyProperties似乎创建了一个对象的克隆。如果是这样的话,那么关于实现可克隆接口(只有不可变对象是新的,因为可变对象复制了引用)的关注点是什么?哪一个是最好的,为什么 我昨天实现了cloneable,然后意识到我必须为非字符串/Primative元素提供自己的修改。然后我被告知我现在正在使用的BeanUtils.copyProperties。这两种实现似乎都提供了类似的功能 感谢克隆创建对象的浅层副本,克隆对象始终与原始对象属于同一类。将复制所有字段,
BeanUtils.copyProperties
似乎创建了一个对象的克隆。如果是这样的话,那么关于实现可克隆接口(只有不可变对象是新的,因为可变对象复制了引用)的关注点是什么?哪一个是最好的,为什么
我昨天实现了cloneable,然后意识到我必须为非字符串/Primative元素提供自己的修改。然后我被告知我现在正在使用的BeanUtils.copyProperties
。这两种实现似乎都提供了类似的功能
感谢克隆创建对象的浅层副本,克隆对象始终与原始对象属于同一类。将复制所有字段,无论是否为专用字段 copyProperties API将属性值从源bean复制到目标bean,用于所有属性名称相同的情况
对我来说,这两个概念几乎没有共同之处。Josh Bloch提供了一些相当好的论据(包括您提供的论据),断言
可克隆性
从根本上说是有缺陷的,而倾向于使用复制构造函数。看
我还没有遇到复制不可变对象的实际用例。您复制对象是出于特定的原因,可能是为了将一些可变对象集隔离到单个事务中进行处理,从而保证在该处理单元完成之前,任何东西都不能改变它们。如果它们已经是不可变的,那么引用就和副本一样好
BeanUtils.copyProperties通常是一种不需要修改类即可进行复制的不那么麻烦的方法,它在合成对象方面提供了一些独特的灵活性
也就是说,copyProperties
并不总是一刀切。在某些时候,您可能需要支持包含具有专门构造函数但仍然是可变的类型的对象。您的对象可以支持内部方法或构造函数来解决这些异常,或者您可以将特定类型注册到某个外部工具中进行复制,但它无法到达甚至clone()。这很好,但仍有局限性。从您的问题中,我想您需要对象的深度副本。如果是这种情况,请不要使用方法,因为它已在oracle docs
中指定提供关联对象的浅拷贝。我对BeanUtils.copyProperties
API没有足够的了解。
下面给出的是deepcopy
的简短演示。这里我正在深度复制一个基元数组
。您可以对任何类型的对象尝试此代码
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");
}
}
}
import java.io.*;
类数组副本
{
ByteArrayOutputStream baos;
ByteArrayInputStream垃圾箱;
public void saveState(Object obj)引发异常//将对象的字节流保存到“ObjectOutputStream”。
{
bas=新的ByteArrayOutputStream();
ObjectOutputStream oos=新的ObjectOutputStream(BAS);
oos.writeObject(obj);
oos.close();
}
public int[][]readState()引发异常//使用`ObjectInputStream'将状态读回对象`
{
bins=newbytearrayinputstream(baos.toByteArray());
ObjectInputStream oins=新ObjectInputStream(箱);
Object obj=oins.readObject();
oins.close();
返回(int[])obj;
}
公共静态void main(字符串[]args)引发异常
{
int arr[][]={
{1,2,3},
{4,5,7}
};
arraydepcopy ars=新的arraydepcopy();
System.out.println(“保存状态…”);
ars.saveState(arr);
System.out.println(“状态保存…”);
System.out.println(“检索状态…”);
int j[][]=ars.readState();
System.out.println(“State retrieved..,检索到的数组是:”);
对于(int i=0;i
BeanUtils比标准克隆更灵活,标准克隆只是将字段值从一个对象复制到另一个对象。clone方法从同一类的bean复制字段,但是BeanUtils可以对具有相同属性名的不同类的两个实例执行此操作
例如,让我们假设您有一个Bean a,它有一个字段字符串date,还有一个Bean B,它有相同的字段java.util.date。使用BeanUtils,您可以复制字符串值,并使用DateFormat将其自动转换为日期
我用它将SOAP对象转换为Hibernate对象,这些对象的数据类型不同。克隆由您完成。如果您尝试克隆的实例包含另一个实例的引用,那么您也必须将克隆代码写入该实例。
如果实例包含对其他实例的引用链怎么办?
所以,如果你自己克隆,你可能会错过一个小细节
另一方面,BeanUtils.copyProperties会自己处理所有事情。
这会减少你的工作量。我想你是在寻找深度拷贝。您可以在util类中使用下面的方法,并将其用于任何类型的objct
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);
}
}
公共静态T复制(T输入){
ByteArrayOutputStream baos=null;
ObjectOutputStream oos=null;
ByteArrayInputStream bis=null;
ObjectInputStream ois=null;
试一试{
bas=新的ByteArrayOutputStream();
oos=新对象输出流(BAS);
oos.writeObject(输入);
oos.flush();
byte[]bytes=baos.toByteArray();
bis=新的ByteArrayInputStream(字节);
ois=新的ObjectInputStream(bis);
Object result=ois.readObject();
返回(T)结果;
}捕获(IOE异常){
/**
* 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);
}
}
}
}
}
}
writeMethod.invoke(target, value);
class Student {
private String name;
private Address address;
}
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`